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

本文介绍了一种解决经典多路合并问题的算法实现方案。该方案通过使用优先队列维护值,并逐步合并多个数组来找到所有可能组合中最小的k个和。适用于需要从多个数组中选取元素并进行排序的问题。

题意:给出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
*/     


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值