洛谷P1631 序列合并 堆

题目链接:https://www.luogu.com.cn/problem/P1631

这题要我们输出前n小的数,可以用堆来解决。
我们首先可以看出这样一个规律(A序列与B序列都是从小到大排序):
A1+B1<=A1+B2<=A1+B3<=…<=A1+Bn;
A2+B1<=A2+B2<=A2+B3<=…<=A2+Bn;

An+B1<=An+B2<=An+B3<=…<=An+Bn;

我们把A1+B1,A2+B1…An+B1依次放进堆里,每次取出堆顶元素,输出,并把它的A序列元素加上B序列元素的下一个,然后更新小根堆。
代码入下(这里手写堆,也可以用优先队列)

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
int a[maxn],b[maxn];//a序列,b序列
int volume[maxn];//在a序列的位置
int step[maxn];//所需b序列的位置
int heap[maxn];//堆
int n;
void Swap(int x,int y)//交换
{
    int temp=heap[x];
    heap[x]=heap[y];
    heap[y]=temp;
    temp=volume[x];
    volume[x]=volume[y];
    volume[y]=temp;
    temp=step[x];
    step[x]=step[y];
    step[y]=temp;
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        volume[i]=i;
        step[i]=1;
    }
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&b[i]);
    }
    for(int i=1;i<=n;i++)
    heap[i]=b[1]+a[i];
    for(int i=1;i<=n;i++)
    {
        printf("%d ",heap[1]);
        step[1]++;
        heap[1]=a[volume[1]]+b[step[1]];
        int j=1;
        while((j<<1)<=n)//堆排序,有儿子才继续
        {
            int temp=j<<1;
            if(temp<n&&heap[temp]>heap[temp+1])
            temp++;
            if(heap[j]>heap[temp])
            {
                Swap(j,temp);
                j=temp;
            }
            else
            break;
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值