1. 程式人生 > >UVA-10954 Add All

UVA-10954 Add All

bre 貪心 cout 需要 == return targe multi clu

題目鏈接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1895

題目大意:類似於這道題UESTC - 1599

就是將所有的數字最後合並為一個數字,但是每次合並需要的消耗值是等於兩個數的和,求最小的消耗值。

當然是貪心,每次排序後合並最小的兩個值,再題彈出那兩個值,壓入兩值之和。再繼續剛才的步驟,直到只要一個了。

用sort肯定是超時的,會自動排序的容器當然是最好的選擇。用multiset就行。

AC代碼:

 1 #include<iostream>
 2
#include<stdio.h> 3 #include<set> 4 using namespace std; 5 int main() 6 { 7 int n; 8 while(cin>>n) 9 { 10 if(n==0)break; 11 multiset<int> s; 12 multiset<int>::iterator it; 13 int x; 14 for(int i=0;i<n;i++) 15 {
16 scanf("%d",&x); 17 s.insert(x); 18 } 19 long long int body=0; 20 int t; 21 while(s.size()!=1) 22 { 23 it=s.begin(); 24 body+=(*it); 25 t=*it; 26 s.erase(it); 27 it=s.begin();
28 body+=(*it); 29 t+=(*it); 30 s.erase(it); 31 s.insert(t); 32 } 33 cout<<body<<endl; 34 } 35 return 0; 36 }

UVA-10954 Add All