Sequence
Time Limit: 6000MS | Memory Limit: 65536K | |
Total Submissions: 7762 | Accepted: 2565 |
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
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<string> #include<algorithm> #include<cstdlib> #include<queue> #include<vector> #include<stack> using namespace std; int tt,m,n; int a[2010],b[2010],heap[2010]; int main() { scanf("%d",&tt); while(tt--) { scanf("%d%d",&m,&n); for(int i=0;i<n;i++) scanf("%d",&a[i]); sort(a,a+n); m--; while(m--) { for(int i=0;i<n;i++) scanf("%d",&b[i]); sort(b,b+n); for(int i=0;i<n;i++) heap[i]=a[i]+b[0]; make_heap(heap,heap+n); for(int i=1;i<n;i++) { bool ok=0; for(int j=0;j<n;j++) { int temp=a[j]+b[i]; if(temp<heap[0]) { pop_heap(heap,heap+n); heap[n-1]=temp; push_heap(heap,heap+n); ok=1; } else break; } if(!ok) break; } for(int i=0;i<n;i++) a[i]=heap[i]; sort(a,a+n); } for(int i=0;i<n-1;i++) printf("%d ",a[i]); printf("%d\n",a[n-1]); } return 0; }