LUOGUP1631---序列合并

本文介绍了一种使用堆排序的算法实现,并加入剪枝技巧提高效率。通过构建大根堆来快速找到最大值,同时利用剪枝减少不必要的计算,适用于需要频繁查找最大值的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int n;
int hp[1000005];
int z[1000000];
int cnt,acnt=1,bcnt=1;
int a[100005],b[100005];
int mx;
void pus(int x) {//建立大根堆(一直想的建个小根堆后来发现大根堆好用。。。)
    int now=++cnt;
    hp[now]=x;
    while(now>1) {
        int tp=now/2;
        if(hp[now]>hp[tp]) {
            swap(hp[now],hp[tp]);
            now=tp;
        } else break;
    }
}
int del() {//维护堆
    int res=hp[1];
    hp[1]=hp[cnt];
    cnt--;
    int now=1;
    while(now*2<=cnt) {
        int tp=now*2;
        if(hp[tp+1]>hp[tp]&&tp<cnt)tp++;
        if(hp[tp]>hp[now])swap(hp[tp],hp[now]);
        else break;
        now=tp;
    }
    return res;
}
int main() {
    cin>>n;
    for( int i=1; i<=n; i++) {
        scanf("%d",&a[i]);
    }
    for(int i=1; i<=n; i++)
        scanf("%d",&b[i]);
//    memset(hp,0x7f,sizeof hp);//没有必要memset
    hp[1]=214512312;
    for(int i=1; i<=n; i++) {
        for(int j=1; j<=n; j++) {
            int r=a[i]+b[j];
            if(r<hp[1]||cnt<n) {
                pus(r);
                if(cnt>n)del();
                if(cnt==n&&a[i]+b[j+1]>=hp[1])break;//如果b的下一个+a现在的仍大于大根堆的第一个,就没必要继续进行下去了
            }
        }if(cnt==n&&a[i+1]+b[1]>=hp[1])break;//同理
    }
    int ans[100005];
    for(int i=1; i<=n; i++)
        ans[i]=del();
    for(int i=n;i>=1;i--)printf("%d ",ans[i]);
}

一道堆排,然后主要是加了个好像是剪枝的东西。
然后先建起来一个大根堆,来判断是否能入堆。就这样。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值