这题让我无语了,我开始就是用贪心写的,结果t了,我还在想才3e5就t,我也是无语了,后来我又改了一下优先队列,然后AC;
题意:就是给你到town的距离和当前站的油量,让你算从开始的p单位油量到终点最少需要停多少站就能到达终点;
很明显题给的是stop到town的距离所以需要用总距离-给的距离;
思路:把最后终点当做stop只不过dis=总距离,fuel=0;用[0,n]遍历距离;如果距离小于初始油量,那么久放入stop的fuel值到优先队列;如果大于了,那么久一直加到能到当前枚举到的站,才结束循环;所以AC代码:
#include<cstdio>
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
struct Node{
int d,fuel;
}p[100010];
bool cmp(Node a, Node b){
return a.d<b.d;
}
int main(){
int n;
priority_queue<int> q;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d %d",&p[i].d,&p[i].fuel);
}
int dis,all;
scanf("%d %d",&dis,&all);
for(int i=0;i<n;i++){
p[i].d=dis-p[i].d;
}
sort(p,p+n,cmp);
// int Max=0,num=0;//这里就是t的部分,超无语。。。。。。
// while(q.size()){
// if(q.top().d<=all){
// Max=max(q.top().fuel,Max);
// q.pop();
// }else{
// all+=Max;
// Max=0;
// num++;
// if(all>=dis){
// return printf("%d\n",num),0;
// }
// }
// }
// puts("-1");
int num=0;
p[n].d=dis;p[n].fuel=0;//把终点当一个油站
for(int i=0;i<=n;i++){
while(all<p[i].d){//如果油量小于当前可达的距离,那么每次就加上前面all大于油站的距离的fuel的最大值
if(q.empty()){//如果为空,说明根本不能到达这个stop,所以直接输出
return puts("-1"),0;
}else{//不断加
all+=q.top();
q.pop();
num++;
}
}
q.push(p[i].fuel);//这里就是把all所能到达的stop的fuel给入队,并且大的排前面
}
printf("%d\n",num);
return 0;
}