题目大意:
开车从起点到终点,两地距离L,车内只有P个单位汽油,每行驶1个单位距离,消耗1个单位油量。两地有N个加油站,每个加油站只有特定的油量,尽可能少停车,即减少加油的次数,尽快到达终点。
输入样例:
4(4个加油站) 4 4(这个加油站离终点的距离为4个单位,拥有油量4个单位) 5 2(这个加油站离终点的距离为5个单位,拥有油量2个单位) 11 5(......) 15 10(......) 25 10(起点的位置,距离终点25,车内油量10)
输出样例:(若能到达输出最少的加油次数,若不能到达,输出-1)
2(到达终点的过程至少加油2次)
分析:
跳出实际看问题。可以在车没油的时候加油。而此时在车经过的加油站,都是你的选择。要想加油次数最少,贪心思想,选择当前油量最多的加油站加油。油量最多,优先列队。若队列为空还未到达终点,输出-1。
代码<c++>:
#include<stdio.h>
#include<algorithm>
#include <vector>
#include <queue>
#define M 10005
using namespace std;
//燃料站 结构体
typedef struct
{
int len;//距离
int wei;//燃料重量
} Stop;
bool cmp(Stop x,Stop y) //从大到小
{
if(x.len!=y.len) return x.len>y.len;
return x.wei>y.wei;
}
priority_queue<int> q;//定义一个最大堆队列
Stop stop[M];
int main()
{
int N,i,j,count=0,weight,k,max=0;
//freopen("1.txt","r",stdin);
//输入
scanf("%d",&N);//N 燃料站个数
for(i=1; i<N+2; i++)
{
scanf("%d %d",&stop[i].len,&stop[i].wei);//N个燃料站 信息 和 起点时信息
}
//终点信息存入
stop[0].len=0;
stop[0].wei=0;
//排序 (按距离从大到小)
sort(stop,stop+N+2,cmp);
weight=stop[0].wei;//当前搜具有的燃料
i=0;
j=1;
while(i<N+1)
{
while(stop[i].len-stop[j].len<=weight&i<N+1) //有油
{
q.push(stop[j].wei);//入队
weight=weight-(stop[i].len-stop[j].len);
i++;
j++;
}
if(j!=N+2) //没有到达终点
{
if(!q.empty())
{
weight= weight+q.top();//加油
count++;
q.pop();
}
else//队列为空
{
count=-1;
break;
}
}
}
printf("%d",count);
return 0;
}