[P1631] sequences into Luo Gu heap []

Disclaimer: If you want to reprint, can be explained in the comments directly, thank you! https://blog.csdn.net/SSL_ZYC/article/details/90949250

Subject to the effect:

Topic links: https://www.luogu.org/problemnew/show/P1631
There are two lengths n n sequences a a and b b , in a a and b b the sum can be obtained from each of a number n 2 n^2 Ge and, asked this n 2 n^2 th smallest and n n a.


Digression:

AC500 Festival \color{red}\texttt{AC500祭} Here Insert Picture Description

I accuracy rate is really low qwq


Ideas:

As the title says a , b a,b are monotonically increasing. So we can not consider the sort.
Monotonically increasing at the same time meet the special
a [ x ] + b [ 1 ] &lt; a [ x ] + b [ 2 ] < . . . < a [ x ] + a [ n ] ( x [ 1 , n ] ) a[x]+b[1]&lt;a[x]+b[2]&lt;...&lt;a[x]+a[n](x\in [1,n])

So every time we just maintenance n n minimum value can be a number (respectively a [ 1 ] + b [ k 1 ] , a [ 2 ] + b [ k 2 ] , . . . , a [ n ] + b [ k n ] a[1]+b[k_1],a[2]+b[k_2],...,a[n]+b[k_n] , Which k i k_i Show i i 've accomplished maintained b b Array Pointer)
for the minimum may be considered to maintain a small heap root. Each element maintain a triple ( v a l , x , k ) (val,x,k) , indicates that this a [ x ] + b [ k ] a[x]+b[k] value.
in case ( v a l i , x i , k i ) (val_i,x_i,k_i) Is the minimum heap, then the output v a l i val_i Pop-up, and insert ( a [ x i ] + b [ k i + 1 ] , x i , k i + 1 ) (a[x_i]+b[k_i+1],x_i,k_i+1) .
do n n times the above-described method may be.
time complexity O ( n log n ) O(n\log n)


Code:

#include <queue>
#include <cstdio>
#define mp make_pair
using namespace std;

const int N=100010;
int n,a[N],b[N];
priority_queue<pair<int,pair<int,int> > > q;  //pair套pair最为致命(三元组)

int main()
{
	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++)
		q.push(mp(-a[i]-b[1],mp(i,1)));  //插入初始值
	for (int i=1;i<=n;i++)
	{
		printf("%d ",-q.top().first);
		int x=q.top().second.first,y=q.top().second.second;
		q.pop();
		q.push(mp(-a[x]-b[y+1],mp(x,y+1)));
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/SSL_ZYC/article/details/90949250