Sequence用堆排序
Description
Given m sequences, each contains n non-negative integer. Now we may select one number from each sequence to form a sequence with m integers. It's clear that we may get n ^ m this kind of sequences. Then we can calculate the sum of numbers in each sequence, and get n ^ m values. What we need is the smallest n sums. Could you help us?
Input
The first line is an integer T, which shows the number of test cases, and then T test cases follow. The first line of each case contains two integers m, n (0 < m <= 100, 0 < n <= 2000). The following m lines indicate the m sequence respectively. No integer in the sequence is greater than 10000.
Output
For each test case, print a line with the smallest n sums in increasing order, which is separated by a space.
Sample Input
1 2 3 1 2 3 2 2 3
Sample Output
3 3 4
1 #include"iostream" 2 #include"algorithm" 3 #include"ctime" 4 #include"cstdio" 5 #include"cctype" 6 using namespace std; 7 #define maxx 2008 8 int a[maxx],b[maxx],sum[maxx]; 9 int main() 10 { 11 int i,j,k,t,n,m,temp; 12 scanf("%d",&t); 13 while(t--) 14 { 15 scanf("%d%d",&m,&n); 16 for(i=0;i<n;i++) 17 scanf("%d",&a[i]); 18 for(i=1;i<m;i++) 19 { 20 sort(a,a+n); 21 for(j=0;j<n;j++) 22 scanf("%d",&b[j]); 23 for(j=0;j<n;j++) 24 sum[j]=a[j]+b[0]; 25 make_heap(sum,sum+n); 26 for(j=1;j<n;j++) 27 for(k=0;k<n;k++) 28 { 29 temp=b[j]+a[k]; 30 if(temp>=sum[0]) 31 break; 32 pop_heap(sum,sum+n); 33 sum[n-1]=temp; 34 push_heap(sum,sum+n); 35 } 36 for(j=0;j<n;j++) 37 a[j]=sum[j]; 38 } 39 sort(a,a+n); 40 printf("%d",a[0]); 41 for(j=1;j<n;j++) 42 printf(" %d",a[j]); 43 printf("\n"); 44 printf("time :%d\n",clock()); 45 } 46 return 0; 47 }