poj-2442(STL二叉堆的应用)

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

代码 

 #include<cstdio>
 #include<algorithm>
 #include<iostream>
 #define Max 2008
 using namespace std;
 int a[Max],b[Max],sum[Max];
 int main()
 {
     int i,j,k,t,m,n,temp;
     scanf("%d",&t);
     while(t--)
     {
         scanf("%d %d",&m,&n);
         for(i=0;i<n;i++)
             scanf("%d",&a[i]);
         for(i=1;i<m;i++)
         {
             sort(a,a+n);//将数据读入数组a中,并按升序排序。
             for(j=0;j<n;j++)
                 scanf("%d",&b[j]);
             sort(b,b+n);
             for(j=0;j<n;j++)
                 sum[j]=a[j]+b[0];//将b[0] + a[i] ( 0<=i<=n-1)读入sun数组中
             make_heap(sum,sum+n);//用make_heap对sun建堆
             for(j=1;j<n;j++)//然后b[1] + a[i] (0<=i<=n-1),如果b[1] + a[i]比堆sum的顶点大,则退出,否则删除堆的顶点,插入b[1] + a[i]。然后是b[2],...b[n - 1]
             {
                 for(k=0;k<n;k++)
                 {
                     temp=a[k]+b[j];
                     if(temp>=sum[0])
                         break;
                     pop_heap(sum,sum+n);
                     sum[n-1]=temp;
                     push_heap(sum,sum+n);
                 }
             }
             for(j=0;j<n;j++)
                     a[j]=sum[j];
         }
         sort(a,a+n);
         for(j=0;j<n-1;j++)
             printf("%d ",a[j]);
         printf("%d\n",a[j]);
     }return 0;
 }

猜你喜欢

转载自blog.csdn.net/qq_24016309/article/details/88725494