最小的n个和(STL堆的运用)

来源:互联网 发布:国税开票软件下载 编辑:程序博客网 时间:2024/05/02 23:08

最小的n个和Time Limit: 1000 MSMemory Limit: 32768 KTotal Submit: 109(26 users)Total Accepted: 22(19 users)Rating: Special Judge: NoDescription

给定A、B两个数列,各包含n个数,分别从A和B中任意取一个数相加得到和,这样会有n^2种结果(包括重复的),求n^2个结果中前n个最小的和。


Input

有多组测试数据。

对于每组测试数据,第一行为n,第二行为数列A,第三行为数列B。

1<=n<=100000, 0 <= Ai, Bi <= 10^9。

Output

对于每组测试数据,输出一行,包含前n个最小的和,按照升序输出,两数之间用一个空格隔开。

Sample Input
51 3 4 2 07 3 5 2 111074 50 47 45 38 64 19 2 84 6991 46 44 7 67 1 40 60 78 41
Sample Output
2 3 3 4 43 9 20 26 39 42 43 45 46 46
SourceHCPC2014校赛训练赛 3

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <stack>using namespace std;int a[100005];int b[100005];int sum[100005];int main(){#ifdef xxz    freopen("in.txt","r",stdin);#endif // xxz   int n;    while(cin>>n)    {        for(int i = 0; i < n; i++) cin>>a[i];        for(int i = 0; i < n; i++) cin>>b[i];        sort(a,a+n);        sort(b,b+n);        for(int i = 0; i < n; i++) sum[i] = a[0] + b[i];        make_heap(sum,sum+n);        for(int i =1 ; i < n; i++)        {            for(int j = 0; j < n; j++)            {                int t = b[j] + a[i];                if(t > sum[0]) break;                else                {                    pop_heap(sum,sum+n);                    sum[n-1] = t;                    push_heap(sum,sum+n);                }            }        }        sort(sum,sum+n);        for(int i = 0; i < n-1; i++)        {            cout<<sum[i]<<" ";        }        cout<<sum[n-1]<<endl;    }    return 0;}

0 0