• poj2431(优先队列+贪心)


    题目链接http://poj.org/problem?id=2431

    题目大意:一辆卡车,初始时,距离终点L,油量为P,在起点到终点途中有n个加油站,每个加油站油量有限,而卡车的油箱容量无限,卡车在行车途中,每走一个单位的距离消耗一个单位的油量,给定n个加油站距离终点的距离以及油存储量。问卡车是否能到达终点,如果可达,最少需要加多少次油,否则输出-1.

    例:

    输入:

    4
    4 4
    5 2
    11 5
    15 10
    25 10

    输出:

    2

    解题思路:采用贪心的思想,卡车当然在不加油的情况下走的越远越好了,而当它没油时,我们再判断卡车在经过的途中的加油站,哪个加油站加的油最多,选油量最多的,这样后面加油次数也越少,然后又继续行驶,当它又没油了的时候,继续选它从起点到该点所经过的加油站油量最多的加油。

    做法先将加油站到终点的距离由远到近排下序,这样离起点就是由近到远。就是每经过一个加油站就将该加油站的油量压入优先队列中,然后每次没油的时候,去队首元素加油即可。

    附上代码:

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<algorithm>
     5 #include<queue>
     6 using namespace std;
     7 int n,l,p;
     8 struct node{
     9     int dis;
    10     int fuel;
    11     bool operator<(const node &a)const
    12     {
    13         return dis>a.dis;
    14     }
    15 }stop[10005];
    16 priority_queue<int> que;
    17 
    18 int main()
    19 {
    20     cin>>n;
    21     for(int i=0;i<n;i++)
    22         cin>>stop[i].dis>>stop[i].fuel;
    23     cin>>l>>p;
    24     int ans=0;
    25     sort(stop,stop+n);
    26     que.push(p);
    27     int temp=0;
    28     while(l>0&&!que.empty())
    29     {
    30         ans++;
    31         l-=que.top();  //加油 
    32         que.pop();
    33         while(l<=stop[temp].dis&&temp<n)  //将经过的加油站压入优先队列中 
    34             que.push(stop[temp++].fuel);
    35     }
    36     if(l>0) cout<<"-1"<<endl;  //l>0说明到不了终点 
    37     else cout<<ans-1<<endl;  //减去1初始时油箱的油也被计算成一次加油了 
    38     return 0;
    39 }
  • 相关阅读:
    c++ accumulate
    Croc Champ 2013 Round 2 (Div. 2 Edition) B. Ksusha the Squirrel
    ural 1017. Staircases
    ural 1012Kbased Numbers. Version 2 1013. Kbased Numbers. Version 3
    ural 1008. Image Encoding
    ural 1009. Kbased Numbers
    echo命令去掉换行符
    linux中shell 参数变量
    C#中可变字符串StringBuilder和String
    C#异常处理语句
  • 原文地址:https://www.cnblogs.com/zjl192628928/p/9414201.html
Copyright © 2020-2023  润新知