uva11997 K Smallest Sums

148 篇文章 0 订阅
137 篇文章 0 订阅

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 nd the k smallest sums among them. Input
There will be several test cases. The rst 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- le (EOF). Output
For each test case, print the k smallest sums, in ascending order.

以下的内容均对排好序的数组而言。
如果只有两个数组的话,只需要先把a[1]+b[1],a[2]+b[1],…,a[n]+b[1]放入小根堆中,每次取出最小的值之后把他的后继【a值不变,b值取下一个】放入堆中,重复m次就是前m小的。
具体到这道题,只需要把数组两两合并,而且只保留前k小的进行下一次合并,因为最多只取k个,而a[1]+b[1]..a[k]+b[1]一定比a[k+1]+b[1]优,也就是a[k+1]永远用不到。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
int rd()
{
    int x=0;
    char c=getchar();
    while (c<'0'||c>'9') c=getchar();
    while (c>='0'&&c<='9')
    {
        x=x*10+c-'0';
        c=getchar();
    }
    return x;
}
int a[760],b[760],c[760],k;
priority_queue<pair<int,int> > q;
int main()
{
    int i,t;
    pair<int,int> p1;
    while (scanf("%d",&k)==1)
    {
        for (i=1;i<=k;i++)
          a[i]=rd();
        sort(a+1,a+k+1);
        for (t=1;t<k;t++)
        {
            for (i=1;i<=k;i++)
              b[i]=rd();
            sort(b+1,b+k+1);
            while (!q.empty()) q.pop();
            for (i=1;i<=k;i++)
              q.push(make_pair(-a[i]-b[1],1));
            for (i=1;i<=k;i++)
            {
                p1=q.top();
                q.pop();
                c[i]=-p1.first;
                if (p1.second<k)
                  q.push(make_pair(p1.first+b[p1.second]-b[p1.second+1],p1.second+1));
            }
            memcpy(a,c,sizeof(c));
        }
        for (i=1;i<=k;i++)
          printf("%d%c",a[i],i==k?'\n':' ');
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值