HUSTOJ sorted list minimum and

AC a strange experience. . . This question card last week for three days. . .

Portal: http://oj.gdsyzx.edu.cn/problem.php?id=1475

Title Description

Given two ordered list of length n, A and B, taking an element in any of the respective A and B, and a n2 can be obtained, and find the smallest of these n. (Do not go heavy)

Entry

The first row contains an integer n (n <= 400000); the second row and the third row there are n integers, representing ordered tables A and B. Separated by a space between the integer, long integer in the range of size, to ensure that the data sorted list monotonically.

Export

Total n output lines, each line an integer, the i-th small and Behavior i. To ensure that the data in the Long Range.

Sample input

3
1 2 5
2 4 7

Sample Output

3
4
5

This question is the first in the school to do, is go to the "Queue" tab, and then because it is the first n the minimum requirements, then surely it is to use the priority queue.

Let's look at a problem called the k-way merge magical stuff (copy of Baidu library)

 

 

 Yes, we understand the above, the next step! And A and B are considered to all array elements n ordered table (see below)

 

 

If the direct passage merging algorithm in accordance with k, "the current of each table element into a binary heap" log n time required to delete the minimum, the next element is added (all tables) and time required log n, a total need n ^ 2 log n time, data size of 400,000 would definitely burst! ! !

Since it will burst, we have to optimize it. What to think about the elements into a binary heap condition is that it pre-ordered an element in the table is the pop-up (not to be placed)! So we began to sweep + b1 from a1, every time the heap when they are marked with tags, if this element out of the heap, then put it in the next element of the sorted list into a heap!

 

 

 

 

 

In summary, O (n log n)!


Code:

#include <iostream>
#include <queue>
#include <algorithm>

using namespace std;
int n,a[400005],b[400005],t[400005];
struct sb
{
	int h,bj;
	friend bool operator< (sb a1,sb b1)//带结构体的优先队列用法
	{
		return a1.h>b1.h;
	}
};

priority_queue<sb> q;

inline void write(int x)//快速写入
{
     if(x>9) write(x/10);
     putchar(x%10+'0');
}

int main()
{
	ios::sync_with_stdio(0);
	
	cin>>n;
	for(int i=1;i<=n;i++) cin>>a[i];
	for(int i=1;i<=n;i++) cin>>b[i];
	
	for(int i=1;i<=n;i++)
	{
		sb temp;
		temp.h=a[i]+b[++t[i]];
		temp.bj=i;
		q.push(temp);
		write(q.top().h);
		putchar('\n');
		int bjt=q.top().bj;
		if(t[bjt]<n)
		{
			temp.h=a[bjt]+b[++t[bjt]];
			temp.bj=bjt;
		}
		q.push(temp);
		q.pop();
	}
} 

  

Guess you like

Origin www.cnblogs.com/huaruoji/p/12005435.html