#include<bits/stdc++.h>
#define For(i,a,b) for(register int i=(a);i<=(b);++i)
#define Rep(i,a,b) for(register int i=(a);i>=(b);--i)
#define int long long
using namespace std;
inline int read()
{
    char c=getchar();int x=0;bool f=0;
    for(;!isdigit(c);c=getchar())f^=!(c^45);
    for(;isdigit(c);c=getchar())x=(x<<1)+(x<<3)+(c^48);
    if(f)x=-x;return x;
}
 
#define fi first
#define se second
#define pb push_back
#define mkp make_pair
typedef pair<int,int>pii;

#define maxn 200005
#define inf 0x3f3f3f3f
int n,res;
int a[maxn],b[maxn],t[maxn],col[maxn];
int suf[maxn];
signed main()
{
	n=read();
	For(i,1,n){
		a[i]=read(),b[i]=read();
		if((a[i]<=n&&b[i]<=n)||(a[i]>n&&b[i]>n)){
			puts("-1");
			return 0;
		}
		if(a[i]>b[i])swap(a[i],b[i]),col[a[i]]=1;
		t[a[i]]=b[i];
	}
	// get suf max
	suf[n+1]=-1;
	Rep(i,n,1)suf[i]=max(suf[i+1],t[i]);
	int premn=inf;
	int c0=0,c1=0;
	vector<int>v0,v1;
	For(i,1,n)
	{
		premn=min(premn,t[i]);
		if(v0.empty()||t[i]<v0.back()) v0.pb(t[i]),c0+=col[i];
		else if(v1.empty()||t[i]<v1.back()) v1.pb(t[i]),c1+=col[i];
		else {
			puts("-1");
			return 0; 
		}
		if(premn>suf[i+1])
		{
			res+=min(c0+(int)v1.size()-c1,c1+(int)v0.size()-c0);
			c0=c1=0,v0.clear(),v1.clear();
		}
	}
	cout<<res;
	return 0;
}
