您的位置:首页 > 其它

Uva11997——优先队列,多路合并

2013-04-08 08:45 344 查看
题意:给出k个长度为k的整数数组,每个数组里面取一个元素加起来,共有k^k个和,输出这些和的前k个(升序排序后)。

经典的多路合并问题,用一个优先队列维护k个值,每次pop出最小值之后将其下一个值加入队列。但是这题有k个数组,我们可以每次合并两个数组,求出前k个(后面的值我们肯定用不着了),接着再和下一个数组合并。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

const int maxn = 1000;
int arr1[maxn], arr2[maxn], k;
struct pp
{
int s, b;
pp(int aa, int bb) : s(aa), b(bb) { }
bool operator < (const pp & rhs) const { return s > rhs.s; }
};

int main()
{
freopen("in.txt", "r", stdin);
while(~scanf("%d", &k))
{
for(int i = 0; i < k; ++i) scanf("%d", arr1 + i);
sort(arr1, arr1 + k);
for(int i = 1; i < k; ++i)
{
for(int j = 0; j < k; ++j) scanf("%d", arr2 + j);
sort(arr2, arr2 + k);
priority_queue<pp> pq;
for(int j = 0; j < k; ++j) pq.push(pp(arr1[j] + arr2[0], 0));
for(int j = 0; j < k; ++j)
{
pp tem = pq.top(); pq.pop();
arr1[j] = tem.s;
if(tem.b == k - 1) continue;
tem.s = tem.s - arr2[tem.b] + arr2[tem.b + 1];
tem.b++;
pq.push(tem);
}
}
for(int i = 0; i < k - 1; ++i) printf("%d ", arr1[i]);
printf("%d\n", arr1[k - 1]);
}
return 0;
}

/*
3
1 8 5
9 2 5
10 7 6
2
1 1
1 2

9 10 12
2 2
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: