题目描述
有两个长度都是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个最小的和,相邻数字之间用空格隔开。
样例输入
3 2 6 6 1 4 8
样例输出
3 6 7
提示
对于50%的数据中,满足1<=N<=1000;
对于100%的数据中,满足1<=N<=100000。
思维题,运用优先队列可以轻松做出
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int a[100050],b[100050];
struct node
{
int val;
int pos;
friend bool operator < (const node &x,const node &y)
{
return x.val>y.val;
}
};
priority_queue<node>qu;
int main()
{
//freopen("in.txt","r",stdin);
int n;
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]);
}
node op;
for(int i=1;i<=n;i++)
{
op.val=a[1]+b[i];
op.pos=1;
qu.push(op);
}
for(int i=1;i<n;i++)
{
op=qu.top();
qu.pop();
printf("%d ",op.val);
op.val+=(a[op.pos+1]-a[op.pos]);
op.pos++;
qu.push(op);
}
op=qu.top();
printf("%d\n",op.val);
return 0;
}