洛谷 1631 序列合併 堆 解題報告

題目描述

有兩個長度都是N的序列A和B,在A和B中各取一個數相加可以得到N^2個和,求這N^2個和中最小的N個。

輸入輸出格式

輸入格式:

第一行一個正整數N;

第二行N個整數Ai,滿足Ai<=Ai+1且Ai<=10^9;

第三行N個整數Bi, 滿足Bi<=Bi+1且Bi<=10^9.

輸出格式:

輸出僅一行,包含N個整數,從小到大輸出這N個最小的和,相鄰數字之間用空格隔開。

【數據規模】

對於50%的數據中,滿足1<=N<=1000;

對於100%的數據中,滿足1<=N<=100000。

輸入輸出樣例

輸入樣例#1:

3
2 6 6
1 4 8

輸出樣例#1:

3 6 7

思路

感覺STL還是很好用的。
先將a[1]+b[1],a[1]+b[2]+…..+a[1]+b[n]壓入堆中,每次取出堆頂(維護小根堆),將a[i]改成a[i+1],壓回堆中,鑑於剛開始時a,b均爲單調向上,所以a[i]+b[j]必定優於a[i+1]+b[j],所以這種想法可以實現,而每次只動a而不動b則可保證沒有重複。

代碼

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;
const int N=1e5+5;
int n,a[N],b[N];
struct node
{
    int pos,sum;
    friend bool operator < (node a,node b)
    {return a.sum>b.sum;}
}k;
priority_queue<node> q;
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
int main()
{
    n=read();
    for (int i=1;i<=n;i++)
    a[i]=read();
    for (int i=1;i<=n;i++)
    b[i]=read();
    sort(a+1,a+n+1);
    sort(b+1,b+n+1);
    for (int i=1;i<=n;i++)
    {
        k.pos=1;
        k.sum=a[i]+b[1];
        q.push(k);
    } 
    for (int sue=1;sue<=n;sue++)
    {
        node now=q.top();
        q.pop();
        if (now.pos+1<=n)//邊界 
        {
            k.pos=now.pos+1;
            k.sum=now.sum-b[now.pos]+b[k.pos];//換成下一個 
            q.push(k);
        }
        printf("%d ",now.sum);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章