ects your task; just add a set of numbers. But you may feel yourselves
condescended, to write a C/C++ program just to add a set of numbers. Such a problem will simply
question your erudition. So, lets add some
avor of ingenuity to it.
Addition operation requires cost now, and the cost is the summation of those two to be added. So,
to add 1 and 10, you need a cost of 11. If you want to add 1, 2 and 3. There are several ways
1 + 2 = 3, cost = 3 1 + 3 = 4, cost = 4 2 + 3 = 5, cost = 5
3 + 3 = 6, cost = 6 2 + 4 = 6, cost = 6 1 + 5 = 6, cost = 6
Total = 9 Total = 10 Total = 11
I hope you have understood already your mission, to add a set of integers so that the cost is minimal.
Input
Each test case will start with a positive number, N (2 N 5000) followed by N positive integers
(all are less than 100000). Input is terminated by a case where the value of N is zero. This case should
not be processed.
Output
For each case print the minimum total cost of addition in a single line.
1 #include<cstdio> 2 #include<algorithm> 3 using namespace std; 4 int q1[5010],q2[5010],h1,h2,t,n; 5 int get() 6 { 7 if (h1>n) 8 return q2[h2++]; 9 if (h2>t) 10 return q1[h1++]; 11 if (q1[h1]<=q2[h2]) 12 return q1[h1++]; 13 return q2[h2++]; 14 } 15 int main() 16 { 17 int i,j,k,m,p,q,x,y,z,ans; 18 while (scanf("%d",&n)==1&&n) 19 { 20 for (i=1;i<=n;i++) 21 scanf("%d",&q1[i]); 22 sort(q1+1,q1+n+1); 23 ans=0; 24 h1=h2=1; 25 t=0; 26 for (i=1;i<n;i++) 27 { 28 x=get(); 29 y=get(); 30 ans+=(x+y); 31 q2[++t]=x+y; 32 } 33 printf("%d ",ans); 34 } 35 }
和某年NOIP合并果子一模一样。
思路是贪心,每次取两个最小值相加。
具体实现方法有两种,一种是优先队列,O(nlogn)。
另一种即是本代码。
由于后得到的元素一定比先得到(是得到的,不算原来的)的元素大,所以可以开两个队列。
一个队列放排好序的没动过的元素,另一个放新得到的元素。由于两个队列都是单调递增的,所以取最小元素只要看两个队列头即可。
正当我以为得出了O(n)算法时,突然发现:排序要O(nlogn)。
于是复杂度还是O(nlogn)。