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 <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
priority_queue<int,deque<int>,less<int> > big;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int m,n;
int s1[2001],s2[2001];
scanf("%d%d",&m,&n);
for(int j=0;j<n;j++)
{
scanf("%d",&s1[j]);
}
sort(s1,s1+n);
m--;
while(m--)
{
for(int j=0;j<n;j++)
{
scanf("%d",&s2[j]);
big.push(s1[0]+s2[j]);
}
sort(s2,s2+n);
int k=0;
for(int i=1;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(s1[i]+s2[j]>big.top())
break;
big.pop();
big.push(s1[i]+s2[j]);
}
}
for(int i=n-1;i>=0;i--)
{
s1[i]=big.top();
big.pop();
}
}
for(int i=0;i<n-1;i++)
{
printf("%d ",s1[i]);
}
printf("%d\n",s1[n-1]);
}
return 0;
}