minval
Topic description
There are two sequences A and B of length N. If you add any number in A and B, you can get N2 sums, and find the smallest N of these N2 sums.
enter
Enter a positive integer N (1<=N<=100000) in the first line;
The second row contains N integers Ai and Ai<=109; the third row contains N integers Bi and Bi<=109.
output
The output is only one line, containing n integers, the n smallest sums are output from small to large, and adjacent numbers are separated by spaces.
sample input
51 3 2 4 56 3 4 1 7
Sample output
2 3 4 4 5
source
#include<stdio.h>
#include<queue>
#include<algorithm>
using namespace std;
long long a[100005],b[100005],ans[100005];
int main(){
int N;
//priority_queue<long long,vector<long long>,greater<long long> >q;
priority_queue<long long>q;//The default sorting from small to large
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+N+1);
sort(b+1,b+N+1);
for(int i=1;i<=N;i++)
q.push(a[1]+b[i]);
for(int i=2;i<=N;i++){
for(int j=1;j<=N;j++){
if(a[i]+b[j]<q.top()){
q.pop();
q.push(a[i]+b[j]);
}
else
break;//If the current value is greater than all the values in the queue (because it is a priority queue, as long as it is greater than one value, it is greater than all values), jump out,
//And because the array is sorted from small to large, if the current value is large, the subsequent value will be larger
}
}
int k=1;
while(!q.empty()){//Because the queue is placed from large to small by default, so the output from small to large needs to add an array
ans[k++]=q.top();
q.pop();
}
for(int i=N;i>=1;i--){
if(i==1)
printf("%lld\n",ans[i]);
else
printf("%lld ",ans[i]);
}
return 0;
}