Idea: first sort the gas stations in ascending order.
Add B [I] to the priority queue when passing through a gas station (pre-store the amount of fuel each time it passes through a gas station)
When the fuel tank is empty: 1. If the queue is empty (it can be understood as the pre-storage volume), it cannot reach the next gas station, or reach the destination.
2. Otherwise, the largest element in the queue will be taken out to fuel the car (Greedy idea)
#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<queue>using namespace std;int n,l,p;int t[10005];struct Node{ int a,b; bool operator < (const Node e)const { return e.a>a; }}s[10005];int B[10005];int A[10005];int main(){ //freopen("d:\\test.txt","r",stdin); cin>>n; priority_queue<int>q; for(int i=0;i<n;i++) { scanf("%d%d",&t[i],&s[i].b); } cin>>l>>p; for(int i=0;i<n;i++) { s[i].a=l-t[i]; } sort(s,s+n); for(int i=0;i<n;i++) { A[i]=s[i].a; B[i]=s[i].b; } A[n]=l;B[n]=0; int pos=0,fuil=p,ans=0; for(int i=0;i<=n;i++) { int d=A[i]-pos; while(fuil<d) { if(q.empty()) {cout<<"-1";return 0;} fuil+=q.top(); q.pop(); ans++; } fuil-=d; pos=A[i]; q.push(B[i]); } cout<<ans<<endl; return 0;}
Poj2431 sort dition (sorting + priority queue)