Codevs 1245 最小的N个和

39 篇文章 0 订阅
33 篇文章 0 订阅

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 200005
int 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[]){ ; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

七情六欲·

学生党不容易~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值