uva 11997 K Smallest Sums

原题:
You’re given k arrays, each array has k integers. There are k k ways to pick exactly one element in each array and calculate the sum of the integers. Your task is to find the k smallest sums among them.
Input
There will be several test cases. The first line of each case contains an integer k (2 ≤ k ≤ 750). Each of the following k lines contains k positive integers in each array. Each of these integers does not exceed 1,000,000. The input is terminated by end-of-file (EOF).
Output
For each test case, print the k smallest sums, in ascending order.
Sample Input
3
1 8 5
9 2 5
10 7 6
2
1 1
1 2
Sample Output
9 10 12
2 2

中文:
给你k个数组,每个数组有k个数。现在问你每个数组中取一个数加一起求和,那么最小的前k个是多少?

#include <bits/stdc++.h>
using namespace std;
int k;
vector<int> v[751],ans;
struct item
{
    int s,b;
    item(int s,int b):s(s),b(b){}
    bool operator < (const item &rhs) const
    {
        return s>rhs.s;
    }
};
void ini()
{
    for(int i=1;i<=k;i++)
        v[i].clear();
}

void Merge(vector<int> tmp)
{
    priority_queue<item> pq;
    for(int i=0;i<ans.size();i++)
        pq.push(item(ans[i]+tmp[0],0));
    for(int i=0;i<k;i++)
    {
        item t=pq.top();
        pq.pop();
        ans[i]=t.s;
        int b=t.b;
        if(b+1<k)
            pq.push(item(t.s-tmp[b]+tmp[b+1],b+1));
    }
}

int main()
{
    ios::sync_with_stdio(false);
    while(cin>>k)
    {
        ini();
        for(int i=1;i<=k;i++)
        {
            for(int j=1;j<=k;j++)
            {
                int res;
                cin>>res;
                v[i].push_back(res);
            }
            sort(v[i].begin(),v[i].end());
        }
        ans=v[1];
        for(int i=2;i<=k;i++)
            Merge(v[i]);
        for(int i=0;i<ans.size();i++)
            if(i!=ans.size()-1)
                cout<<ans[i]<<" ";
            else
                cout<<ans[i]<<endl;
    }
    return 0;
}

思路:
训练指南中的例题,想了一会没思路,直接看的答案。想法很巧妙。
假设有两个数组求前k个和最小保存在ans当中,现在有第三个数组,那么三个数组的和的最小值就是把当前保存的前k个最小值加上第三个数组当中的k个值即可。
用优先队列维护前k个最小值,然后用递推的思想每次算出加上第三个数组中第i个值的和即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值