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;
}
贪心策略:
当车燃料没有耗尽的时候,就将沿途路过的加油站全都入队
因为这些加油站是可路过的,且车的邮箱容量无限,所以我们可以看作这些加油站随时都能给车提供油
为了使加油次数最少,每次总选择油量最多的加油站加油,此处使用优先队列
但是题目还是有坑的
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;
}
相关文章推荐
- POJ 2431 Expedition (贪心、优先队列)
- POJ 题目2431 Expedition(贪心,优先队列)
- poj 2431 Expedition 贪心 + 优先队列
- POJ 2431 Expedition (贪心+优先队列)
- POJ 2431 Expedition (贪心、优先队列)
- POJ 2431 Expedition (贪心+优先队列)
- poj 2431 Expedition 贪心 + 优先队列
- POJ 2431 - Expedition (贪心 优先队列)
- POJ2431 Expedition (贪心,优先队列)
- poj 2431 Expedition (贪心+优先队列)
- POJ 2431 Expedition 贪心 + 优先队列
- POJ 2431 Expedition (贪心+优先队列)
- POJ 2431 Expedition(贪心+优先队列)
- POJ 2431 Expedition (贪心 + 优先队列)
- poj 2431 Expedition 贪心 + 优先队列
- POJ 2431 Expedition 优先队列+贪心
- poj 2431 Expedition (贪心加优先队列)
- poj 2431 Expedition 贪心+优先队列
- poj2431 Expedition 贪心+优先队列
- POJ 2431 Expedition (汽车加油问题,STL_优先队列+贪心) (挑战程序P76)