P1631 序列合并

题面:https://www.luogu.org/problemnew/show/P1631

本题的n²个和为
A[1]+B[1] <= A[1]+B[2] <= … <= A[1]+B[N]
A[2]+B[1] <= A[2]+B[2] <= … <= A[2]+B[N]
……
A[N]+B[1] <= A[N]+B[2] <= … <= A[N]+B[N]
接下来,就相当于要将这N个有序队列进行合并排序:
首先,将这N个队列中的第一个元素放入一个堆中;
然后;每次取出堆中的最小值。若这个最小值来自于第k个队列,那么,就将第k个队列的下一个元素放入堆中。

Code:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<ctime>
#include<queue>
using namespace std;
const int N=100005;
int n,a[N],b[N];
struct Node{
    int x,id,t;
};
bool operator < (Node p,Node q){
    return  p.x>q.x;
}
priority_queue<Node> Q;
int main(){
    scanf("%d",&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+1+n);
    sort(b+1,b+1+n);
    for(int i=1;i<=n;i++){
        Q.push((Node){a[1]+b[i],i,1});
    }
    for(int i=1;i<=n;i++){
        printf("%d ",Q.top().x);
        int d=Q.top().id;
        int m=Q.top().t+1;
        Q.pop();
        Q.push((Node){a[m]+b[d],d,m});
    }
    return 0;
}
posted @ 2019-07-16 13:43  prestige  阅读(112)  评论(0编辑  收藏  举报