#agc055e. [agc055_e]Set Merging

[agc055_e]Set Merging

Problem Statement

You have NN sets S1,S2,ldots,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=iS_i = \\{i\\}).

You are allowed to perform the following operation:

  • Choose any ii with 1leileN11 \\le i \\le N-1. Let U=SicupSi+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,ldots,Ri1,RiS_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

  • 1leNle5cdot1051 \\le N \\le 5\\cdot 10^5
  • 1leLileRileN1 \\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\\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.


Sample Input 1

3
1 2
1 2
1 3

Sample Output 1

-1

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


Sample Input 2

4
1 3
1 4
1 4
2 4

Sample Output 2

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\\}$