【Turn】Sequence merge (Luogu P1631)

【Turn】Sequence merge (Luogu P1631)

Sequence merge

Title description

There are two sequences A and B whose length is N. Add a number from A and B to get N^2 sums. Find the smallest N of these N^2 sums.

Input format

A positive integer N in the first line;

The second line of N integer Ai, satisfies Ai<Ai+1, and Ai<10^9;

Third line N individual integer Bi, content Bi <Bi + 1, and Bi <10 ^ 9;

[Data Scale]

For 50% of the data, satisfy 1<=N<=1000;

For 100% of the data, 1<=N<=100000 is satisfied.


The solution to this problem is hard to think of; first arrange the A sequence and B sequence in order (from small to large), and then put all b[1]+a[i] (i from 1 to n) into the queue, and Put i into the team (the coordinates of a are also into the team). Obviously, a structure is used. STL has a more convenient pair, which is equivalent to the structure; then it is out of the n-th team, and the number is the smallest each time. The sum, when coming out, enter the team after the subscript of the number that left the team;

Double experience

Code:

#include<bits/stdc++.h>
#define LL long long
using namespace std;
int a[100100];
int b[100100];
priority_queue< pair<int,int>,vector< pair<int,int> >,greater< pair<int,int> > >qu;
int to[100100];
int main(){
    
    
	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]);
	for(int i=1;i<=n;i++) to[i]=1;
	for(int i=1;i<=n;i++) qu.push(pair<int,int>(a[i]+b[1],i));
	while(n--){
    
    
		printf("%d ",qu.top().first);
		int s=qu.top().second;
		qu.pop();
		qu.push(pair<int,int>(a[s]+b[++to[s]],s));
	}
	return 0;
}	

Guess you like

Origin blog.csdn.net/weixin_44338712/article/details/108112577