Codevs 1245 最小的N个和

来源:互联网 发布:js设置div背景图片 编辑:程序博客网 时间:2024/05/22 13:49

1245 最小的N个和

时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamond
题目描述 Description
有两个长度为 N 的序列 A 和 B,在 A 和 B 中各任取一个数可以得到 N^2 个和,求这N^2 个和中最小的 N个。
输入描述 Input Description
第一行输入一个正整数N;第二行N个整数Ai 且Ai≤10^9;第三行N个整数Bi,且Bi≤10^9
输出描述 Output Description
输出仅一行,包含 n 个整数,从小到大输出这 N个最小的和,相邻数字之间用
空格隔开。
样例输入 Sample Input
5
1 3 2 4 5
6 3 4 1 7
样例输出 Sample Output
2 3 4 4 5
数据范围及提示 Data Size & Hint
【数据规模】 对于 100%的数据,满足 1≤N≤100000。

xxy加强了一下数据

#include<cstring>#include<cstdio>#include<iostream>#include<algorithm>using namespace std;#define MAXN 200005int a[MAXN],b[MAXN],heap[MAXN],tot,n;inline void read(int &x){    x=0; int f=1; register char c=getchar();    while(c>'9'||c<'0'){ if(c=='-')f=-1; c=getchar(); }    while(c>='0'&&c<='9'){ x=x*10+c-'0'; c=getchar(); } x*=f;}inline void Insert(int x) {    heap[++tot]=x;    int now=tot,next;    for(;now>1;now=next){        next=now>>1;        if(heap[next]>=heap[now]) break;        swap(heap[next],heap[now]);    }    return ;}void Pop(){    heap[1]=heap[tot--];    int now=1,son;    for(;now<<1 <= tot;now=son){        son=now<<1;        if(son<tot&&heap[son]<heap[son+1]) ++son;        if(heap[son]<=heap[now]) break;        swap(heap[now],heap[son]);    }}int Main(){    freopen("hahaha.in","r",stdin);    freopen("hahaha.out","w",stdout);    read(n);    int tmp,cnt=0;    for(int i=1;i<=n;++i) read(a[i]);    for(int i=1;i<=n;++i) read(b[i]);    sort(a+1,a+n+1);sort(b+1,b+1+n);    for(int i=1;i<=n;++i){        for(int j=1;j<=n;++j){            tmp=a[i]+b[j];            if(cnt<n) Insert(tmp),++cnt;            else {                if(tmp>=heap[1]) break;                else Pop(),Insert(tmp);            }        }    }    sort(heap+1,heap+tot+1);    for(int i=1;i<=n;++i) printf("%d\n",heap[i]);    fclose(stdin);fclose(stdout);    return 0;}int Aptal_is_My_Son=Main();int main(int argc,char *argv[]){ ; }