F - Sequence
Time Limit: 6000 MS Memory Limit: 65536 KB
64-bit integer IO format: %I64d , %I64u Java class name: Main
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<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<string.h>
#include<math.h>
#define maxn 2005
#define inf 0x3f3f3f3f
#define Min(a,b) a<b?a:b
using namespace std;
int a[maxn];//看了别人的题解才会的。。。
int b[maxn];
int main()
{
int t;
cin>>t;
while(t--)
{
int n,m;
priority_queue<int , vector<int> ,less<int> >q;//维护一个最大堆
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)
{
scanf("%d",&a[i]);
}
sort(a,a+m);
for(int i=1;i<n;i++)
{
for(int j=0;j<m;j++)
{
scanf("%d",&b[j]);
q.push(a[0]+b[j]);
}
sort(b,b+m);//这里直接将b数组排序可以优化
for(int k=1;k<m;k++)
{
for(int l=0;l<m;l++)
{
int tem=a[k]+b[l];
if(tem<q.top())
{
q.pop();
q.push(tem);
}
else break;//如果当前值大于堆顶可以直接跳出循环
}
}
int cnt=0;
while(!q.empty())//清空队列
{
a[cnt++]=q.top();
q.pop();
}
sort(a,a+m);
}
for(int i=0;i<m;i++)
{
printf("%d",a[i]);
if(i==m-1)printf("\n");
else printf(" ");
}
}
}