Problem:


Score : 1500 points

Problem Statement

There is an undirected connected graph with N vertices numbered 1 through N.
The lengths of all edges in this graph are 1.
It is known that for each i (1≦i≦N), the distance between vertex 1 and vertex i is A_i, and the distance between vertex 2 and vertex i is B_i.
Determine whether there exists such a graph.
If it exists, find the minimum possible number of edges in it.

Constraints

2≦N≦10^5

0≦A_i,B_i≦N-1

Input

The input is given from Standard Input in the following format:

N
A_1 B_1
A_2 B_2
:
A_N B_N

Output

If there exists a graph satisfying the conditions, print the minimum possible number of edges in such a graph. Otherwise, print -1.

Sample Input 1

4
0 1
1 0
1 1
2 1

Sample Output 1

4

The figure below shows two possible graphs. The graph on the right has fewer edges.

Sample Input 2

3
0 1
1 0
2 2

Sample Output 2

-1

Such a graph does not exist.



Sample input:
4
0 1
1 0
1 1
2 1


Sample output:
4

Submission status: Wrong Answer

Solution code:
n = input()
D = [tuple(map(int, raw_input().split())) for i in xrange(n)]
if (not D[0][0] == D[1][1] == 0 or not D[0][1] == D[1][0] > 0
        or any(i>1 and (d[0] == 0 or d[1] == 0) for i, d in enumerate(D))):
    print -1
    exit(0)
m = {}
for i, d in enumerate(D):
    m[d] = m.get(d, 0) + 1 if i>0 else 0
D.sort()
used = [0]*n

cnt = 0
for x, y in D:
    if (x+1, y+1) in m:
        cnt += m[x+1, y+1]
        m[x+1, y+1] = 0
    if (x+1, y-1) in m:
        cnt += m[x+1, y-1]
        m[x+1, y-1] = 0
ok = 1
for x, y in D:
    if m[x, y] > 0:
        if (x-1, y) not in m or (x, y-1) not in m:
            ok = 0
if ok:
    print 2*n - 2 - cnt
else:
    print -1

Submission status: Runtime Error

Solution code:
n = input()
D = [tuple(map(int, raw_input().split())) for i in xrange(n)]
if (not D[0][0] == D[1][1] == 0 or not D[0][1] == D[1][0] > 0
        or any(i>1 and (d[0] == 0 or d[1] == 0) for i, d in enumerate(D))):
    print -1
    exit(0)
m = {}
for i, d in enumerate(D):
    m[d] = m.get(d, 0) + 1 if i>0 else 0
P = D[:2]
D.sort()

cnt = 0
for x, y in D:
    if (x+1, y+1) in m:
        cnt += m[x+1, y+1]
        m[x+1, y+1] = 0
    if (x+1, y-1) in m:
        cnt += m[x+1, y-1]
        m[x+1, y-1] = 0

def dfs(x, y, dd, used):
    used.add((x, y))
    for dx, dy in dd:
        nx = x + dx; ny = y + dy
        if (nx, ny) in m and (nx, ny) not in used:
            dfs(nx, ny, dd, used)
usedA = set(); usedB = set()
dfs(P[0][0], P[0][1], [(1, 1), (1, 0), (1, -1)], usedA)
dfs(P[1][0], P[1][1], [(1, 1), (0, 1), (-1, 1)], usedB)
if len(m) == len(usedA) == len(usedB):
    print 2*n - 2 - cnt
else:
    print -1