跳到正文

个人记录

洛谷 - P1631

Chthohepta约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年7月15日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 2 分钟

版本

  1. v1当前

大意

有两个长度为 nn 的单调不降序列 aa, bb 在 aa, bb 中各取一个数相加可以得到 n2n^2 个和,求这 n2n^2 个和中最小的 nn 个。

思路

由于 aa,bb 是递增的,所以 ai+bj≤ai+bj+1a_i + b_j \le a_i + b_{j + 1} ,用优先队列维护最小值

代码

C++
#include <bits/stdc++.h>
#define ll long long
using namespace std;

const int N = 1e5 + 3;
int n;
ll a[N], b[N], cnt;
vector <ll> ans;
priority_queue <ll> q;

int main(){
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);

    cin >> n;
    for(int i = 1; i <= n; i ++) cin >> a[i];
    for(int i = 1; i <= n; i ++) cin >> b[i];

    for(int i = 1; i <= n; i ++){
        for(int j = 1; j <= n; j ++){
            if(q.size() < n) q.push(a[i] + b[j]);
            else{
                if(q.top() > a[i] + b[j]) q.pop(), q.push(a[i] + b[j]);
                else break;///由于 a[i] + b[j] 不能计入答案,由思路中的公式可知 a[i] + b[j + 1] 到 a[i] + b[n] 都不可能计入答案
            }
        }
    }

    for(int i = 1; i <= n; i ++){
        ans.push_back(q.top()), q.pop();
    }
    reverse(ans.begin(), ans.end());
    for(int i = 1; i <= n; i ++) cout << ans[i - 1] << ' ';

    return 0;
}
原文