#pragma warning(disable:4996)
#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
int a[751][751];
int k;
//归并思路:
//归并两个有序的数组A[],B[]
//首先把所有的A[i]+B[1]放入优先队列,然后开始取出
//每次取出优先队列里的top时,例如top=A[i]+B[j],就把A[i]+B[j+1]放入优先队列
//node里的sum就是A[i]+B[j], node里的 i 就是 j
struct node{
int sum, i;
node(int s, int ii) :sum(s), i(ii){}
bool operator<(const node &op)const{
return sum>op.sum;
}
};
void merge(int id){
//把第1个数组和第id个数组归并,归并后的数组放到第1个数组
priority_queue<node>q;
for (int i = 1; i <= k; i++){
q.push(node(a[1][i] + a[id][1], 1));
}
for (int i = 1; i <= k; i++){
a[1][i] = q.top().sum;
if (q.top().i + 1 <= k)
q.push(node(q.top().sum - a[id][q.top().i] + a[id][q.top().i + 1], q.top().i + 1));
q.pop();
}
}
int main()
{
while (scanf("%d", &k) != EOF){
for (int i = 1; i <= k; i++){
for (int j = 1; j <= k; j++){
scanf("%d", &a[i][j]);
}
sort(a[i] + 1, a[i] + k + 1);
}
for (int i = 2; i <= k; i++){
merge(i);
}
printf("%d", a[1][1]);
for (int i = 1; i < k; i++)printf(" %d", a[1][i + 1]);
printf("\n");
}
return 0;
}
UVA 11997 K Smallest Sums(优先队列)
最新推荐文章于 2024-05-20 17:12:12 发布