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
题意:m个长度为n的序列,每次从一个序列中选出一个,总共有n^m个,求前n个;
几近暴力的解法, 用 stl 里面的 Heap 即可
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<string>
#include<bitset>
#include<ctime>
#include<deque>
#include<stack>
#include<sstream>
typedef long long ll;
using namespace std;
typedef unsigned long long int ull;
#define maxn 200005
#define ms(x) memset(x,0,sizeof(x))
#define Inf 0x7fffffff
#define inf 0x3f3f3f3f
const long long int mod = 1e9 + 7;
#define pi acos(-1.0)
#define pii pair<int,int>
#define eps 1e-5
#define pll pair<ll,ll>
ll quickpow(ll a, ll b) {
ll ans = 1;
while (b > 0) {
if (b % 2)ans = ans * a%mod;
b = b / 2;
a = a * a%mod;
}
return ans;
}
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a%b);
}
int a[maxn], b[maxn], tot[maxn];
int main() {
//ios::sync_with_stdio(false);
int m, n;
int t;
//cin >> t;
scanf("%d", &t);
while (t--) {
//cin >> m >> n;
scanf("%d%d", &m, &n);
int i, j;
ms(a); ms(b); ms(tot);
for (i = 0; i < n; i++) {
//cin >> a[i];
scanf("%d", &a[i]);
}
for (i = 1; i < m; i++) {
sort(a, a + n);
for (j = 0; j < n; j++) {
//cin >> b[j];
scanf("%d", &b[j]);
}
sort(b, b + n);
for (j = 0; j < n; j++)
tot[j] = a[j] + b[0];
make_heap(tot, tot + n);
for (j = 1; j < n; j++) {
for (int k = 0; k < n; k++) {
int tmp = a[k] + b[j];
if (tmp >= tot[0]) {
break;
}
pop_heap(tot, tot + n);
tot[n - 1] = tmp;
make_heap(tot, tot + n);
}
}
for (j = 0; j < n; j++)
a[j] = tot[j];
}
sort(a, a + n);
for (i = 0; i < n - 1; i++)
cout << a[i] << ' ';
cout << a[n - 1] << endl;
}
}