atcoder#AGC055E. [AGC055E] Set Merging

[AGC055E] Set Merging

Score : 15001500 points

Problem Statement

You have NN sets S1,S2,,SNS_1, S_2, \ldots, S_N. Initially, for each ii from 11 to NN, set SiS_i contains only integer ii (that is, Si={i}S_i = \{i\}).

You are allowed to perform the following operation:

  • Choose any ii with 1iN11 \le i \le N-1. Let U=SiSi+1U = S_i \cup S_{i+1} ー the union of sets SiS_i and Si+1S_{i+1}. Then, replace both SiS_i and Si+1S_{i+1} with UU.

You want to perform a finite number of operations above (maybe zero), to get a configuration, in which Si={Li,Li+1,,Ri1,Ri}S_i = \{L_i, L_i+1, \ldots, R_i-1, R_i\} for all ii from 11 to NN. Is it possible to reach this configuration? If it is possible, also find the smallest number of operations needed to reach it.

Constraints

  • 1N51051 \le N \le 5\cdot 10^5
  • 1LiRiN1 \le L_i \le R_i \le N

Input

Input is given from Standard Input in the following format:

NN

L1L_1 R1R_1

L2L_2 R2R_2

\vdots

LNL_N RNR_N

Output

If it is possible to reach the required configuration, output the smallest number of operations needed to do it. Otherwise, output -1.

3
1 2
1 2
1 3
-1

It can be proved that it's impossible to obtain the required configuration.

4
1 3
1 4
1 4
2 4
4

We can perform the following sequence of operations:

  • Choose i=2i = 2, get $S_1 = \{1\}, S_2 = \{2, 3\}, S_3 = \{2, 3\}, S_4 = \{4\}$
  • Choose i=1i = 1, get $S_1 = \{1, 2, 3\}, S_2 = \{1, 2, 3\}, S_3 = \{2, 3\}, S_4 = \{4\}$
  • Choose i=3i = 3, get $S_1 = \{1, 2, 3\}, S_2 = \{1, 2, 3\}, S_3 = \{2, 3, 4\}, S_4 = \{2, 3, 4\}$
  • Choose i=2i = 2, get $S_1 = \{1, 2, 3\}, S_2 = \{1, 2, 3, 4\}, S_3 = \{1, 2, 3, 4\}, S_4 = \{2, 3, 4\}$