CF BUDDY
← Problems·

1027F · Session in BSU

2400 · binary search, dfs and similar, dsu

Problem: Polycarp studies in Berland State University. Soon he will have to take his exam. He has to pass exactly nn exams.

For the each exam ii there are known two days: aia_i — day of the first opportunity to pass the exam, bib_i — day of the second opportunity to pass the exam (ai<bia_i < b_i). Polycarp can pass at most one exam during each day. For each exam Polycarp chooses by himself which day he will pass this exam. He has to pass all the nn exams.

Polycarp wants to pass all the exams as soon as possible. Print the minimum index of day by which Polycarp can pass all the nn exams, or print -1 if he cannot pass all the exams at all.

Input Format: The first line of the input contains one integer nn (1n1061 \le n \le 10^6) — the number of exams.

The next nn lines contain two integers each: aia_i and bib_i (1ai<bi1091 \le a_i < b_i \le 10^9), where aia_i is the number of day of the first passing the ii-th exam and bib_i is the number of day of the second passing the ii-th exam.

Output Format: If Polycarp cannot pass all the nn exams, print -1. Otherwise print the minimum index of day by which Polycarp can do that.

Sample Cases

Case 1

Input

2
1 5
1 7

Output

5

Case 2

Input

3
5 13
1 5
1 7

Output

7

Case 3

Input

3
10 40
40 80
10 80

Output

80

Case 4

Input

3
99 100
99 100
99 100

Output

-1

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback