题意:有一辆车,油箱容量无限,要出发去一个城镇,途中有n个加油站,汽车每行驶一单位距离消耗一单位汽油,每个加油站都有一个最大加油量的限制,你可以选择在任何一个你经过的加油站加油,问在保证能到达城镇的前提下,最少加几次油,当不能到达城镇输出-1;
输入:第一行一个数字 n,表示一个加油站, 第2 到 n+1 行 每行 2 个数字,表示加油站距离城镇的距离 和 加油限度。最后一行 起始汽车距离城镇的距离 和 油量。输入不保证 距离的单调性。
考虑到距离最大才 1000000(100w) 开个数组足够, 于是我用空间复杂度换取时间复杂度。直接桶排加油站,这样在某个距离 有加油站时,那么 d[这个距离] 就不为 0;以此来 确定路过的加油站。把路过的加油站推入优先队列中,如果没油了,就从优先队列中取出最大的油量的加油站加上 ,这样的效果等同于 在路过那个加油站的时候 加上了油。
代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int MAXN = 1000000 + 10;
int dis[MAXN];
priority_queue <int> q;
int main()
{
int n;
scanf("%d",&n);
for(int i = 1; i <= n; i ++)
{
int a, b;
scanf("%d%d",&a,&b);
dis[a] = b;
}
int L, P, ans = 0;
scanf("%d%d",&L, &P);
while(L > 0)
{
if(dis[L])
q.push(dis[L]);
if(!P)
{
if(!q.empty())
{
P += q.top();
q.pop();
ans ++;
}
else{
puts("-1");
return 0;
}
}
P --;
L --;
}
printf("%d\n",ans);
return 0;
}
还有一种解法就是 用数组记录 加油站,然后排序。
评测结果的话这个比较优。
代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
const int MAXN = 10000 + 10;
struct Gas_Station{
int l, p;
}gas[MAXN];
priority_queue <int> q;
bool cmp(Gas_Station a, Gas_Station b)
{
return a.l > b.l;
}
int main()
{
int n;
scanf("%d",&n);
for(int i = 1; i <= n; i ++)
scanf("%d%d", &gas[i].l, &gas[i].p);
sort(gas+1, gas+n+1, cmp);
int L, P, ans = 0, cnt = 1;
scanf("%d%d",&L, &P);
while(L > 0)
{
if(L == gas[cnt].l)
{
q.push(gas[cnt].p);
cnt ++;
}
if(!P)
{
if(!q.empty())
{
P += q.top();
q.pop();
ans ++;
}
else{
puts("-1");
return 0;
}
}
P --;
L --;
}
printf("%d\n",ans);
return 0;
}