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 }
分类:
OJ
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步