uva11997 K Smallest Sums

来源:互联网 发布:电脑桌面知乎 编辑:程序博客网 时间:2024/06/05 03:22

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