POJ-2442 Sequence

来源:互联网 发布:跳跃网络枪界 编辑:程序博客网 时间:2024/05/17 09:12
Sequence
Time Limit: 6000MS Memory Limit: 65536KTotal Submissions: 8855 Accepted: 2937

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 linesindicate(表明) 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

12 31 2 32 2 3

Sample Output

3 3 4

思路:

先输入一组数据,与第二组数据分别求和。将和储存在一个大顶堆里,如果相加和大于堆顶,则删除堆顶,加入新数,重新构造堆。
最后将堆当做第一组数据,重复上一步。
本题用了C++的 STL 。

代码:

#include<algorithm>#include<iostream>using namespace std;const int N = 2001;int a[N], b[N], sum[N];int main(){ios::sync_with_stdio(false);int T;cin>>T;while(T--){int m, n;cin>>m>>n;for(int i = 0;i < n;i++)cin>>a[i];for(int i = 1;i < m;i++){sort(a,a+n);for(int j = 0;j < n;j++)cin>>b[j];sort(b,b+n);for(int j = 0;j < n;j++)sum[j] = a[j] + b[0];make_heap(sum,sum+n);for(int j = 1;j < n;j++){for(int k = 0;k < n;k++){int temp = a[k] + b[j];if(temp >= sum[0])break;pop_heap(sum,sum+n);sum[n-1] = temp;push_heap(sum,sum+n);}}for(int j = 0;j < n;j++)a[j] = sum[j];}sort(a,a+n);int i;for(i = 0;i < n-1;i++)cout<<a[i]<<' ';cout<<a[i]<<endl;}return 0;}


0 0
原创粉丝点击