您的位置:首页 > 产品设计 > UI/UE

POJ 2442 Sequence

2015-08-14 11:12 435 查看
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

/*

题目大意:

题目大意是这样的(读题读了好半天),给定M个序列,每个序列有N个数,从每一个序列中挑选出一个数来便有M个数,将这M个数相加,通过这样的加和算法可以有N^M个和,输出的是这N^M个和中最小的N个。

解题思路:

第一个序列我们先将他存在一个数组中,从第二个序列开始计算,注意看的时候思路是一行一行的看,不能看全局。

拿样例来说,第一行为1 2 3 ,存在ans[]数组中并从小到大排序。从第二列开始,第一个数是2,将ans[]数组的数依次加上2不更改ans[]中的值存在优先队列(大->小)中,这样现在队列中有数据为5 4 3,ans[]中依旧为1 2 3,然后读入第二个数字2,再依次和ans[]中的数相加,第一次相加得到1+2为3,优先队列中最大的队头为5,所以符合要求,替换掉5,5出队列,3入队列,一直加到ans[]数组的最后。此时队列中为4 3 3,ans[]数组为1 2 3,下面在读取第三个数组为3,和第一个数相加为4,等于队头,不替换直接跳出,因为ans数组有序越加越大浪费时间没有必要。处理到每一列的最后一个数结束后要将ans数组更新,再去判断下一个序列,知道全部结束,输出ans[]数组就可以。

*/

#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <queue>
#include <stack>
#include <cmath>
#include <vector>
#include <cstdio>
#include <map>
#include <set>
const int INF = 0x3f3f3f3f;

using namespace std;

int ans[2010];

int main()
{
int n,m,t,ant;
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&n,&m);
priority_queue<int,vector<int>,less<int> >Q;
for(int i=0; i<n; i++)
{
if(!i)
{
for(int j=0; j<m; j++)
scanf("%d",&ans[j]);
sort(ans,ans+m);
}
else
{
for(int j=0; j < m; j++)
{
scanf("%d",&ant);
if(!j)
for(int k=0; k<m; k++)
Q.push(ant+ans[k]);
else
{
for(int k=0; k<m; k++)
{
if(ant+ans[k] < Q.top())
{
Q.pop();
Q.push(ant+ans[k]);
}
else
break;
}
}
}
int k = m-1;
while(Q.size())
{
ans[k--] = Q.top();
Q.pop();
}
}
}
for(int k=0; k<m; k++)
printf(k==0?"%d":" %d",ans[k]);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: