Sequence
Time Limit: 6000MS | Memory Limit: 65536K | |
Total Submissions: 8313 | Accepted: 2718 |
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
2 2 3 1 2 3 2 2 3
Sample Output
3 3 4
10 10 21 12 123 3 21 123 32 143 43 56 2 32 43 34 54 56 656 76 43 234 234 45 5 65 56 76 43 23 435 57 32 324 435 46 56 76 87 78 43 23 3 32 324 45 56 57 34 23 54 565 23 32 34 342 324 232 2 432 324 12 234 324 4 45 65 67 435 23 5 654 34 3245 345 56 56 657 67 456 345 325 234 234 546 65 88 66 53 654 65 765 5 3 34 34 34 56 345 234 2 34 131 132 132 133 134 135 140 140 141 141
题目大意:从每一行中取出一个数与另一行相加,使得数最小的一个序列
思路:先用一个数组,储存第行的序列,然后再设另一个来储存其他。先用次行的第一个数和第一行的每个数相加。放入优先队列(从大到小中),再用次行的第二个数与第一行相加,和优先队列的数比较。比原来的数小的话则,弹出最大元素并放进队。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<algorithm>
#define LL long long
#define inf 0x3f3f3f3f
using namespace std;
int s1[200002],s[200002];
int main()
{
int n,m,i,j,cla,k;
priority_queue<int>q;//,vector<int >,less<int> >q;//如果省略后两个的话就是默认的less排
scanf("%d",&cla);
while(cla--)
{
int sum=0;
while(!q.empty())
q.pop();
scanf("%d%d",&m,&n);
for(i=0;i<n;i++)
scanf("%d",&s1[i]);
for(i=1;i<m;i++)
{
sort(s1,s1+n);//进行处理的时候要先排序
for(j=0;j<n;j++)
{
scanf("%d",&s[j]);
}
for(j=0;j<n;j++)//先用次行的第一个数,处理前两行
q.push(s[0]+s1[j]);
int tmp;
for(j=1;j<n;j++)//再用第次行的2~n分别与前一行相加并和之前队列中的数相比较
{
for(k=0;k<n;k++)
{
tmp=s[j]+s1[k];
if(tmp>=q.top())//如果有一个比最大的数大的话就停止(有一个数满足这个性质,那么当前数+其他数,也一定比原来队列的大)
break;
else//否则进队,因为他就是求前n个最小的数,所以可以不断的排除大数,进小数
{
q.pop();
q.push(tmp);
}
}
}
int sum=0;
while(!q.empty())
{
s1[sum++]=q.top();
q.pop();
}
}
sort(s1,s1+n);
for(i=0;i<n;i++)
i==n-1?printf("%d\n",s1[i]):printf("%d ",s1[i]);
}
}