【codevs1245】最小的 N 个和

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

题解:由于数据量是 10W,必须减少每次选取的决策集合中元素的个数。可以发现,将两个序列的元素排好序之后,固定 i 时,对于任意的 j<k,有 \(a[i]+b[j]<a[i]+b[k]\)。因此,可以将序列分成 N 组,第 i 组表示 \(a[i]+b[j],j\in[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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值