zoukankan      html  css  js  c++  java
  • UVA10954:Add All(优先队列)

    题目:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=68990#problem/O

    题目需求:在数组中拿出两个数相加,再把结果放回数组中再如此反复,求最小的结果是多少。

    题目解析:典型的哈弗曼编码的题目。和之前做过的合并果子如出一辙,因为优先队列写的有点少,所以看了以前的代码。

    #include <iostream>
    #include <string.h>
    #include <stdio.h>
    #include <algorithm>
    #include <math.h>
    #include <queue>
    #define eps 1e-9
    typedef long long ll;
    using namespace std;
    int a[5010];
    int main()
    {
        int n;
        while(scanf("%d",&n)!=EOF&&n!=0)
        {
            priority_queue<int, vector<int>, greater<int> >q;
            while(!q.empty()) q.pop();
            ll m=0;
            for(int i=0; i<n; i++)
            {
                scanf("%d",&a[i]);
                q.push(a[i]);
                m+=a[i];
            }
            ll sum,sum1,co=0;
            while(!q.empty())
            {
                sum=q.top();
                sum1=0;
                q.pop();
                co+=sum;
                if(!q.empty())
                {
                    sum1=q.top();
                    q.pop();
                }
                else break;
                sum=sum+sum1;
                co+=sum1;
                q.push(sum);
            }
            printf("%d
    ",co-m);
        }
        return 0;
    }
  • 相关阅读:
    re模块
    collections模块
    hashlib模块
    序列号模块
    random模块
    sys模块
    OS模块
    工厂模式
    Go语言之直接选择排序
    Go语言之直接插入排序
  • 原文地址:https://www.cnblogs.com/zhangmingcheng/p/4270306.html
Copyright © 2011-2022 走看看