您的位置:首页 > 其它

POJ 2431 Expedition(贪心+优先队列)

2017-08-18 16:56 357 查看
题目链接:点击打开链接

贪心策略:

当车燃料没有耗尽的时候,就将沿途路过的加油站全都入队

因为这些加油站是可路过的,且车的邮箱容量无限,所以我们可以看作这些加油站随时都能给车提供油

为了使加油次数最少,每次总选择油量最多的加油站加油,此处使用优先队列

但是题目还是有坑的

1. 距离是到目的地的距离,所以需要拿出来减;

2. 不一定是严格递增的,所以还需要按距离进行排序,注意简单的O(N^2)的排序会让它跪掉;

AC代码如下(141MS)

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;

struct fuelStop{
int A, B;
int operator<(const fuelStop& o)const
{
return A>o.A;
}
};

int main()
{
priority_queue<int> que;
int L, N, P;
fuelStop stop[10005];

while(cin>>N)
{
for(int i=1;i<=N;++i)
cin>>stop[i].A>>stop[i].B;
cin>>L>>P;

for(int i=N;i>=1;--i)
stop[i].A = L-stop[i].A;
sort(stop+1,stop+1+N);
stop[0].A = L;
stop[0].B = 0;

int ans = 0, cur = 0;
int i;
if(N==0) N = 1;
for(i=N;i>=0;--i)
{
int d = stop[i].A - cur;
while(d>P)
{
if(que.empty()) { i=-1; break; }
else
{
P += que.top();
que.pop();
ans++;
}
}
P -= d;
cur = stop[i].A;
if(i) que.push(stop[i].B);
}
if(i==-1) cout<<ans<<endl;
if(i==-2) puts("-1");
while(!que.empty()) que.pop();
for(int i=1;i<=N;++i)
stop[i].A=stop[i].B=0;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: