Sequence
Time Limit: 6000MS | Memory Limit: 65536K | |
Total Submissions: 9136 | Accepted: 3040 |
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
Source
POJ Monthly,Guang Lin
///2442
/// 题目意思就是给你一个n*m的矩阵 每行拿出来一个元素一共组成 n^m个数字求最小的m个数字
///下文m n混了...不影响实际.....
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn=2222;
int n,m;
int mod[maxn],num[maxn];
void Find()
{
priority_queue <int> q; ///利用优先队列维护mod数组 即答案序列
int i,j;
for (i=1; i<=m; i++)
{
q.push(mod[i]+num[1]); ///将num序列最小的放进去 "模板"
}
for (i=1; i<=m; i++)
{
for (j=2; j<=m; j++)
{
int x=mod[i]+num[j]; ///遍历加和
if(x<q.top())
{
q.pop();
q.push(x);
}
else
{
break;///从小到大排序 所以第一个小的不符合后面就不用看了
}
}
}
for (i=m; i>=1; i--) /// 因为大的优先级高 所以倒序存入mod继续参加之后的加和过程
{
mod[i]=q.top();
q.pop();
}
}
int main()
{
int t,i,j;
cin>>t;
while (t--)
{
cin>>n>>m;
for(i=1; i<=m; i++)
{
cin>>mod[i];
}
sort(mod+1,mod+1+m); ///从小到大排序
for (i=1; i<n; i++)
{
for (j=1; j<=m; j++)
{
cin>>num[j];
}
sort(num+1,num+1+m); ///排序
Find();
}
for (i=1; i<m; i++)
{
cout<<mod[i]<<" ";
}
cout<<mod[m]<<endl;
}
return 0;
}