NYOJ 55 懒省事的小明(优先队列)

来源:互联网 发布:清华北大 知乎 编辑:程序博客网 时间:2024/05/16 01:36

懒省事的小明

题目来源:点击打开链接

题目信息:由题意可知,每次都让最小的进行合并,再把合并的值放回队列中,如此循环...力气才最小

                  该题运用到了优先队列,先设定优先级,优先级大的先出对。和 “看病要排队”  颇为相似。

                  在“看病要排队”该问题中有对优先队列的简单介绍,这是连接:点击打开链接

注意:该题的测试数据较大,最后的力气数sum要定义为长整形,我就在这浪费了一次AC机会

源代码:

#include<stdio.h>#include<stdlib.h>#include<queue>#include<algorithm>using namespace std;struct cmp{    bool operator()(const int a,const int b){        //a的优先级比b小时返回true.        return a>b; //这里表示a的优先级比b小    }};int main(){    priority_queue<int,vector<int>,cmp>gz;  //定义优先队列    int N;    scanf("%d",&N);    while(N--)    {        int n,x,i,a,b;        long long sum=0;    //注意,一定要定义成长整形        scanf("%d",&n);        for(i=0;i<n;i++)    //将果子堆数入队列        {            scanf("%d",&x);            gz.push(x);        }        if(n==1)            printf("%d\n",x);        else        {            while(gz.size()!=1)            {                a=gz.top();                gz.pop();                b=gz.top();                gz.pop();                a=a+b;                sum+=a;                gz.push(a);            }            printf("%lld\n",sum);        }        while(!gz.empty())            gz.pop();    }    return 0;}


0 0