PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000050. Khôi phục hàng đợi theo chiều cao (Queue Reconstruction by Height)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Khôi phục hàng đợi theo chiều cao (Queue Reconstruction by Height)

Queue Reconstruction by Height

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

The original order of a queue of nn people has been lost. For each person, you are given a pair (hi,ki)(h_i,k_i):

  • hih_i is their height.
  • kik_i is the number of people before them in the correct queue whose heights are greater than or equal to hih_i.

Reconstruct a queue using all nn given people so that every person's requirement is satisfied. The front position is position 11, but no positions should be printed. If several queues are valid, any one is acceptable; each input pair must be used with exactly its given multiplicity.

At least one valid reconstruction is guaranteed.

Input

  • Line 1: integer nn, the number of people.
  • Next nn lines: two integers hi,kih_i,k_i describing one person per line; the input order is not the final queue order.

Output

Print exactly nn lines from the front to the back of the queue, each containing a person’s integers h,kh,k. Use exactly the supplied multiset of pairs and satisfy each person’s count of earlier people with height at least hh.

Subtasks

Subtask 1 (20 points):

  • 1≤n≤201\le n\le 20; 0≤hi≤1060\le h_i\le 10^6; 0≤ki<n0\le k_i<n for every 1≤i≤n1\le i\le n; a valid arrangement of all nn people exists.

Subtask 2 (30 points):

  • 1≤n≤5001\le n\le 500; 0≤hi≤1060\le h_i\le 10^6; 0≤ki<n0\le k_i<n for every 1≤i≤n1\le i\le n; a valid arrangement of all nn people exists.

Subtask 3 (50 points):

  • 1≤n≤20001\le n\le 2000; 0≤hi≤1060\le h_i\le 10^6; 0≤ki<n0\le k_i<n for every 1≤i≤n1\le i\le n; a valid arrangement of all nn people exists.

Examples

Examples 1

Input

6
7 0
4 4
7 1
5 0
6 1
5 2

Output

5 0
7 0
5 2
6 1
4 4
7 1

Explanation

In the output queue, (5,0)(5,0) has nobody before it. (7,0)(7,0) has no previous person of height at least 77. (5,2)(5,2) has two preceding people of height at least 55. (6,1)(6,1) has only the preceding height-77 person. (4,4)(4,4) has four qualifying predecessors. The final (7,1)(7,1) has exactly one preceding person with height at least 77.

Examples 2

Input

3
6 0
5 0
4 0

Output

4 0
5 0
6 0

Explanation

In queue [4,5,6][4,5,6], each person is taller than all earlier people, so every person has zero qualifying predecessors.

Placing a person of height 66 before someone of height 55 or 44 would give that later person at least one preceding person of greater or equal height, contradicting k=0k=0. Hence the valid increasing-height order is (4,0)(4,0), (5,0)(5,0), (6,0)(6,0).