两个堆排序——洛谷P1631 序列合并

本文提供洛谷P1631题目的两种解决方案,包括使用贪心算法与堆排序的方法一,以及利用小根堆进行优化的方法二。通过详细代码示例,展示了如何高效解决此问题。

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

题目:https://www.luogu.org/problemnew/show/P1631
题解
方法一:将所有情况视为n*n的二维表格,然后贪心+堆排序

#include<cstdio>  
#include<queue>   
using namespace std;
int a[100005]={}, b[100005]={}, to[100005]={},i, n;
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > >q;
int main()
{
    scanf("%d", &n);
    for (i = 1; i <= n; i++)
        scanf("%d", &a[i]);
    for (i = 1; i <= n; i++)
    {
        scanf("%d", &b[i]); to[i] = 1;
        q.push(pair<int, int>(a[1] + b[i], i));
    }
    while (n--)
    {
        printf("%d ", q.top().first);
        i = q.top().second; q.pop();
        q.push(pair<int, int>(a[++to[i]] + b[i], i));
    }
    return 0;
}

方法二

#include<queue>
#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 100005;
struct data{
    int x, y, v;
    bool operator <(const data &y) const{
        return v > y.v;//小根堆 
    }
};
int n, a[N], b[N], X[N], Y[N];
priority_queue<data> pq;
//在结构体中重定义小于号,维护一个小根堆
int read()
{
    int x = 0;
    bool f = 0;
    char ch = getchar();
    while(!isdigit(ch)) {
        if(ch == '-') f = 1;
        ch = getchar();
    }
    while(isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ '0'), ch =getchar();
    return !f ? x : -x;
}
//优雅的读入优化
int main()
{
    scanf("%d",&n);
    data x, y, k;
    int tot = n;
    for(int i = 1; i <= n; i++) scanf("%d",&a[i]);
    for(int i = 1; i <= n; i++) scanf("%d",&b[i]);
    sort(a + 1, a + n + 1);
    sort(b + 1, b + n + 1);
    for(int i = 1; i <= n; i++) k.x = k.y = i, k.v = a[i] + b[i], pq.push(k);//初始化压入 
    for(int i = 1; i <= n; i++)
    {
        k = pq.top(); pq.pop();
        printf("%d ", k.v);
        if(k.x == k.y)
        {
            x.x = k.x; x.y = k.y + 1; x.v = a[x.x] + b[x.y]; pq.push(x);
            y.x = k.x + 1; y.y = k.y; y.v = a[y.x] + b[y.y]; pq.push(y);
        }
        else
        {
//为什么 i<j 时不压入 a[i+1]+b[j] ?
//我们考虑到此时 a[i+1]+ b[j-1] 及之前的数字可能依旧在优先队列中并且更优,就不必更新。
            if(k.x > k.y) y.x = k.x + 1, y.y = k.y, y.v = a[y.x] + b[y.y], pq.push(y);
                else x.x = k.x, x.y = k.y + 1, x.v = a[x.x] + b[x.y], pq.push(x);
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值