zoukankan      html  css  js  c++  java
  • poj 2431 优先队列,贪心

    题意:从当前位置到目的地,给出初始油量和距离,给出一系列的加油站离终点的距离和可以加的油量,每走一个单位消耗一个单位油量,求要到达目的地最少要在几个加油站下车加油。

    题解:既然是最少,那么尽可能在油消耗完的时候给加油,如果再走a米的路程中注定要加一次油,那么就选择这段路程油量最大的加油站下车

    代码实现就是每经过一个加油站将这个加油站的油量存下来, 等到不得不下车加油的时候,就选择储存的这些数据中最大的那个(不一定是在油刚刚消耗完的时候,在那之前也行),并且选择完了以后将这个数据移出。直到到达目的地。

    代码如下:

    #include <stdio.h>
    #include <stdlib.h>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    struct Node
    {
        int num;
        Node* next;
    };
    struct Point
    {
        int dist;
        int fuel;
    };
    Node *root;
    int n;
    int L, res;
    void input(Node *a)
    {
        Node *beg = root;
        while(beg->next != NULL && beg->next->num >= a->num) beg = beg->next;
        a->next = beg->next;
        beg->next = a;
    }
    bool cmp(const Point a, const Point b)
    {
        if(L - a.dist != L - b.dist) return L - a.dist < L - b.dist;
        return a.fuel < b.fuel;
    }
    Node *newnode(){return (Node*)malloc(sizeof(Node*));}
    int main()
    {
        while(scanf("%d", &n) != EOF)
        {
            root = (Node *)malloc(sizeof(Node *));
            root->num = 0xffffff;
            root->next = NULL;
            Point p[10005];
            for(int i = 0; i < n; i++)
            {
                scanf("%d%d", &p[i].dist, &p[i].fuel);
            }
    
            scanf("%d%d", &L, &res);
            sort(p, p + n, cmp);
            Node *n0 = newnode();
            n0->num = res;
            input(n0);
            int ii = 0;
            int cango = 0;
            int ans = -1;
            while(root->next != NULL)
            {
                Node *n1 = root->next;
                root->next = n1->next;
                cango += n1->num;
                //printf("cango = %d
    ", cango);
                ans++;if(cango >= L)break;
    
                for(; L - p[ii].dist <= cango; ii++)
                {
                    Node *n0 = newnode();
                    n0->num = p[ii].fuel;
                    input(n0);
                }
            }
            if(cango < L) cout << "-1" << endl;
            else printf("%d
    ", ans);
    
        }
    }

    可以用c++中的容器优先队列

    priority_queue。
    print “ 欢迎来到渣小狼的博客,这既是博客,也是日记,里面记录了小狼的学习经历还有一些小狼的见解,非常希望每一个来到这里的人能够留下只言片语,更加的希望留下的是对于小狼的不足的补充,谢谢(*^__^*) 嘻嘻……”
  • 相关阅读:
    动态设置字体大小需要注意的点
    getDimension与getDimensionPixelOffset与getDimensionPixelSize的区别
    统计图钻取的明细报表在非模态窗口中显示
    局部区块多个报表 TAB 页切换及局部区块的参数查询
    分栏报表制作攻略
    多值关联过滤
    鼠标悬停出现提示信息怎么做
    复杂报表设计之动态报表
    Logo(图片)作为报表水印的解决方法
    分组填报表的制作
  • 原文地址:https://www.cnblogs.com/wolf-yasen/p/6565532.html
Copyright © 2011-2022 走看看