Sequence 优先队列模拟堆 poj 2442

来源:互联网 发布:广联达电力计价软件 编辑:程序博客网 时间:2024/04/24 19:56
Sequence
Time Limit: 6000MSMemory Limit: 65536KTotal Submissions: 6381Accepted: 1998

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

12 31 2 32 2 3

Sample Output

3 3 4

Source

 

这是用优先队列来模拟堆,这个题意是说用2行3列的矩阵,那么我们就会形成3^2个选择,我们先把第一行放入

num1中,然后把第二行的数据赋给num2,让num2[0]和num1[ ]相加得出的值放入优先队列big中,放入big中

再与num2[i](i>=1)+num1[ ]和比较,如果小于最大值,就把最大值直接替换,这样最后就可以得出来前n个序列

中最大的值了

 

#include<iostream>#include<cstdio>#include<cstring>#include<queue>#include<algorithm>#include<vector>using namespace std;int main(){    int num1[3000];    int num2[3000];    priority_queue<int,vector<int>,less<int> >big;    //´    int t,i,j,k;    int m,n;    scanf("%d",&t);    while(t--)    {      scanf("%d%d",&m,&n);      for(i=0;i<n;i++)      scanf("%d",&num1[i]);      sort(num1,num1+n);      int l,y;      for(y=1;y<m;y++)      {          for(j=0;j<n;j++)          {              scanf("%d",&num2[j]);              big.push(num1[0]+num2[j]);          }          sort(num2,num2+n);          for(k=1;k<n;k++)          {              for(l=0;l<n;l++)              {                  if(num1[k]+num2[l]>big.top())                  {                     break;                  }                  big.pop();                  big.push(num1[k]+num2[l]);              }          }          for(k=0;k<n;k++)          {              num1[n-k-1]=big.top();              big.pop();          }      }       for(i=0;i<n-1;i++)       printf("%d ",num1[i]);       printf("%d\n",num1[i]);    }    return 0;}


 

 

0 0