【codevs1245】最小的 N 个和

题目大意:给定两个有 N 个数字的序列,从这两个序列中任取一个数相加,共有 (N^2) 个和,求这些和中最小的 N 个。

题解:由于数据量是 10W,必须减少每次选取的决策集合中元素的个数。可以发现,将两个序列的元素排好序之后,固定 i 时,对于任意的 j<k,有 (a[i]+b[j]<a[i]+b[k])。因此,可以将序列分成 N 组,第 i 组表示 (a[i]+b[j],jin[1,n]),根据刚才的发现可知,每次的决策集合中元素个数只有 N 个,要从这 N 个元素中选择最小的一个作为答案的一部分,可以采用堆来维护。

代码如下

#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define all(x) x.begin(),x.end()
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int dx[]={0,1,0,-1};
const int dy[]={1,0,-1,0};
const int mod=1e9+7;
const int inf=0x3f3f3f3f;
const int maxn=1e5+10;
const double eps=1e-6;
inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
inline ll sqr(ll x){return x*x;}
inline ll read(){
    ll x=0,f=1;char ch;
    do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
    do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
    return f*x;
}
/*--------------------------------------------------------*/
typedef pair<int,P> pi;// val row col

int n,a[maxn],b[maxn];
priority_queue<pi,vector<pi>,greater<pi>> q;

void read_and_parse(){
    n=read();
    for(int i=1;i<=n;i++)a[i]=read();
    for(int i=1;i<=n;i++)b[i]=read();
}

void solve(){
    for(int i=1;i<=n;i++)q.push(mp(a[i]+b[1],mp(i,1)));
    for(int i=1;i<=n;i++){
        pi res=q.top();q.pop();
        printf("%d ",res.fi);
        P tmp=res.se;
        q.push(mp(a[tmp.fi]+b[tmp.se+1],mp(tmp.fi,tmp.se+1)));
    }
    puts("");
}

int main(){
    read_and_parse();
    solve();
    return 0;
}

原文地址:https://www.cnblogs.com/wzj-xhjbk/p/10031139.html