#include <cstdlib>
#include <iostream>
#include <cstdio>
#include <math.h>
#include <cstring>
#include <time.h>
#include <complex>
#include <algorithm>
#include <queue>
#include <stack>
#include <unordered_map>
#include <set>
#include <bitset>

#pragma warning(disable:4996)
#define PII std::pair<long long, long long>
#define PTT std::pair<tree *, tree *>

template<typename T> T min(T x, T y)
{
	return x < y ? x : y;
}
template<typename T> T max(T x, T y)
{
	return x > y ? x : y;
};

const long long INF = 2000000005;//00000;// autojs.org
const long long mod = 1000000007;// 998244353;//
const long long MAXN = 500005;

int N;
int a[MAXN][2], f[MAXN], mn[MAXN], mx[MAXN];
bool s[MAXN];

void solve()
{
	for (int i = 1; i <= N; i++)
		if (f[i] <= N)
		{
			printf("-1\n");
			return;
		}
	int ans = 0;
	for (int l = 1, r; l <= N; l = r + 1)
	{
		r = l;
		while (r < N && mn[r] < mx[r + 1])
			r++;
		int t1 = INF, t2 = INF, n = 0;
		for (int j = l; j <= r; j++)
		{
			if (f[j] < t1)
				t1 = f[j], n += !s[j];
			else if (f[j] < t2)
				t2 = f[j], n += s[j];
			else
			{
				printf("-1\n");
				return;
			}
		}
		ans += min(n, r - l + 1 - n);
	}
	printf("%d\n", ans);
}
void init()
{
	scanf("%d", &N);
	for (int i = 1; i <= N; i++)
	{
		scanf("%d %d", a[i], a[i] + 1);
		f[a[i][0]] = a[i][1];
		f[a[i][1]] = a[i][0];
		if (a[i][0] < a[i][1])
			s[a[i][0]] = true;
	}
	mn[1] = f[1], mx[N] = f[N];
	for (int i = 2; i <= N; i++)
		mn[i] = min(mn[i - 1], f[i]);
	for (int i = N - 1; i >= 1; i--)
		mx[i] = max(mx[i + 1], f[i]);
}

int main()
{
	init();
	solve();

	return 0;
}