洛谷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;
}

猜你喜欢

转载自blog.csdn.net/weixin_44491423/article/details/104514172