Sequence
Time Limit: 6000MS | Memory Limit: 65536K | |
Total Submissions: 5448 | Accepted: 1666 |
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
题意:给你n*m的矩阵,然后每行取一个元素,组成一个包含n个元素的序列,一共有n^m种序列,
让你求出序列和最小的前n个序列的序列和。
解题步骤:
1.将第一序列读入data1向量中,并按升序排序。
2.将数据读入data2向量中,并按升序排序。
将data2[0] + data1[i] ( 0<=i<=n-1)读入dataq向量中
建堆。
然后data2[1] + data1[i] (0<=i<=n-1),如果data2[1] + data1[i]比堆dataq的顶点大,则退出,否则删除
堆的顶点,插入data2[1] + data1[i]。然后是data2[2],...data2[n - 1]
3.将dataq的数据拷贝到data1中,并对data1按升序排序
4.循环2,3步,直到所有数据读入完毕。
5.打印data1中的数据即为结果。
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int t;
int n,m;
int num1[2010];
int num2[2010];
priority_queue<int,deque<int>,less<int> > big;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&m,&n);
for(int i=0;i<n;i++)
scanf("%d",&num1[i]);
sort(num1,num1+n);
for(int i=1;i<m;i++)
{
for(int j=0;j<n;j++)
{
scanf("%d",&num2[j]);
big.push(num1[0]+num2[j]);
}
sort(num2,num2+n);
for(int k=1;k<n;k++)
for(int l=0;l<n;l++)
{
if(num1[k]+num2[l]>big.top())
break;
big.pop();
big.push(num1[k]+num2[l]);
}
for(int k=0;k<n;k++)
{
num1[n-k-1]=big.top();
big.pop();
}
}
printf("%d",num1[0]);
for(int i=1;i<n;i++)
printf(" %d",num1[i]);
puts("");
}
}