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 3Sample Output
3 3 4
题意:有m组序列,每组有n个数,从每一组去一个数求和,输出n个最小和。
思路:优先队列维护最小和,从小到大排序,遍历。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
int a[2018],b[2018];
int main()
{
int t,n,m,i,j,k;
cin>>t;
int sum;
while(t--)
{
sum=0;
priority_queue<int>q;
cin>>m>>n;
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=1;i<m;i++)
{
sort(a,a+n);
for(j=0;j<n;j++)
{
cin>>b[j];
}
for(j=0;j<n;j++)
{
q.push(a[j]+b[0]);
}
for(j=1;j<n;j++)
{
for(k=0;k<n;k++)
{
sum=a[k]+b[j];
if(sum>=q.top())//因为是从小到大排序,所以比堆里的大就不符合。
{
break;
}
else
{
q.pop();
q.push(sum);
}
}
}
int num=0;
while(!q.empty())
{
a[num++]=q.top();
q.pop();
}
}
sort(a,a+n);//输出时也要排序
for(i=0;i<n;i++)
{
if(i==n-1)
{
cout<<a[i]<<endl;
}
else
{
cout<<a[i]<<" ";
}
}
}
}