zoukankan      html  css  js  c++  java
  • UVA 10954 Add All (优先队列的妙用)

    题目大意:给出n个数,要将n个数相加,每次相加所得的值为当次的计算量,完成所有的求和运算后,要求总的计算量最小。

     

    解题思路:只要每次挑选最小的两个数出来相加就可以了,然后将和当成新的一个数放回数组。

    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <algorithm>
    #include <queue>
    
    using namespace std;
    
    int n,x;
    
    int main()
    {
        ios::sync_with_stdio(false);cin.tie(0);
        while(cin>>n&&n!=0){
            ///greater<int>表示数值小的优先级越大
            priority_queue<int,vector<int>,greater<int> >q;///优先队列按照从小到大排序
            for(int i=0;i<n;i++){
                cin>>x;
                q.push(x);
            }
            int ans=0;
            for(int i=0;i<n-1;i++){
                int a=q.top();q.pop();
                int b=q.top();q.pop();
                ans+=a+b;
                q.push(a+b);
            }
            cout<<ans<<endl;
        }
        return 0;
    }
  • 相关阅读:
    ZOJ 3490 String Successor
    ZOJ 3465 The Hive
    ZOJ 3077 Move to Baggage Office
    ZOJ 2836 Number Puzzle
    POJ 2115 C Looooops
    ZOJ 3605 Find the Marble
    扩展欧几里德
    搭配飞行员(网络流)
    最小费用流
    最大流
  • 原文地址:https://www.cnblogs.com/Fy1999/p/9396408.html
Copyright © 2011-2022 走看看