UVA 11997 - K Smallest Sums
题意:给定k个数组,每个数组k个数字,要求每个数字选出一个数字,构成和,这样一共有kk种情况,要求输出最小的k个和
思路:其实只要能求出2组的前k个值,然后不断两两合并就可以了,因为对于每两组,最后答案肯定是拿前k小的去组合。然后问题就变成怎么求2组下的情况了,利用一个优先队列维护,和作为优先级,先把原数组都从小到大排序好了,那么先把a[i] + b[0] (i < k)入队,然后往后取k个,每次取完之后,拿最小那个在把b往后推一个,这样保证每次队列中都会有当前的最小值存在,利用优先队列取出即可,总复杂度为O(k2log(k))
代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 755;
int n, a[N][N];
struct State {
int b, sum;
State() {}
State(int b, int sum) {
this->b = b;
this->sum = sum;
}
bool operator < (const State& c) const {
return sum > c.sum;
}
};
void merge(int *a, int * b) {
priority_queue<State> Q;
for (int i = 0; i < n; i++)
Q.push(State(0, a[i] + b[0]));
for (int i = 0; i < n; i++) {
State now = Q.top();
a[i] = now.sum;
Q.pop();
Q.push(State(now.b + 1, now.sum - b[now.b] + b[now.b + 1]));
}
}
int main() {
while (~scanf("%d", &n)) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
scanf("%d", &a[i][j]);
sort(a[i], a[i] + n);
}
for (int i = 1; i < n; i++)
merge(a[0], a[i]);
for (int i = 0; i < n - 1; i++)
printf("%d ", a[0][i]);
printf("%d\n", a[0][n - 1]);
}
return 0;
}