UVA 10954 Add All

题意:在正整数集合中每次选2个数相加,加n-1次,加后把结果放入集合,把两个数除去,输出每次加的总和;

思路:用优先队列存集合,greater是小顶堆,每次取出最小的两个数就行了。

 1 #include<iostream>
 2 #include<functional>
 3 #include<queue>
 4 using namespace std;
 5 
 6 int n,m;
 7 int res=0;
 8 void work(priority_queue<int,vector<int>,greater<int> > &pq)
 9 {
10     res=0;
11     while(pq.size()>1)
12     {
13         int n1=pq.top();
14     //    cout<<"n1="<<n1<<endl; 
15         pq.pop();
16         int n2=pq.top();
17     //    cout<<"n2="<<n2<<endl; 
18         pq.pop();
19         int sum=n1+n2;
20         res+=sum;
21         pq.push(sum);
22     }
23 }
24 int main()
25 {
26 
27     while(cin>>n&&n)
28     {
29         priority_queue<int,vector<int>,greater<int> >pq;
30         for(int i=0;i<n;i++)
31         {
32             cin>>m;
33             pq.push(m);
34         }
35         work(pq);
36         cout<<res<<endl;
37     }
38     return 0;
39 }

猜你喜欢

转载自www.cnblogs.com/fudanxi/p/10430825.html