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.

Solution in C++14 (GCC 5.4.1) (judge verdict: Wrong Answer)

#include<bits/stdc++.h>
#define pii pair<int,int>
#define N 100005
#define fr first
#define se second
#define check(x,y) (mp.find(make_pair(x,y))!=mp.end())
using namespace std;
struct msg{
	int x,y,num;
};
pii v[N];
vector<msg> b[N*2];
map<pii,int > mp;
map<pii,int >::iterator itr;
int dp[N][2];
int n,ans,d;
void end(){
	while(1);
	puts("-1");
	exit(0);
}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d%d",&v[i].first,&v[i].se),mp[v[i]]++;
	d=v[1].se;
	for(itr=mp.begin();itr!=mp.end();itr++){
		b[(itr->fr).fr+(itr->fr).se].push_back((msg){(itr->fr).fr,(itr->fr).se,itr->se});
	}
	for(int i=0;i<d;i++) if(b[i].size()>0) end();
	if(mp[v[1]]!=1||mp[v[2]]!=1||v[1].fr!=0||v[2].se!=0||v[1].se!=v[2].fr) end();
	
	for(int i=d;i<=n*2;i++){
		for(int j=0;j<b[i].size();j++){
			dp[j][0]=dp[j][1]=0x3f3f3f3f;
			if(j==0){
				if(i==d) {dp[j][0]=0;continue;}
				if(check(b[i][j].x-1,b[i][j].y-1)){
					dp[j][0]=dp[j][1]=b[i][j].num;
				}else if(check(b[i][j].x-1,b[i][j].y)){
					dp[j][0]=b[i][j].num;
					if(check(b[i][j].x,b[i][j].y-1))
						dp[j][1]=b[i][j].num*2;
				}else end();
			}else{
				int temp=0x3f3f3f3f;
				if(b[i][j-1].x+1==b[i][j].x)
					temp=dp[j-1][0]+max(b[i][j].num,b[i][j-1].num);
				else if(check(b[i][j].x-1,b[i][j].y))
					temp=dp[j-1][1]+b[i][j].num;
				dp[j][0]=temp;
				
				if(check(b[i][j].x,b[i][j].y-1))
					temp+=b[i][j].num;
				else temp=0x3f3f3f3f;
				if(check(b[i][j].x-1,b[i][j].y-1)) temp=min(temp,min(dp[j-1][1],dp[j][0])+b[i][j].num);
				dp[j][0]=min(dp[j][0],dp[j][1]=temp);
			}
		}
		if(i==d) ans+=dp[b[i].size()-1][0];
		else ans+=dp[b[i].size()-1][1];
		if(ans>1e9) end();
	}
	printf("%d\n",ans);
	return 0;
}