#include <bits/stdc++.h>
using namespace std;

const int N = 2e5 + 5;

int n, f[N], c[N], suf[N];

int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    int a, b;
    scanf("%d%d", &a, &b);
    if ((a <= n && b <= n) || (a > n && b > n)) {
      puts("-1");
      return 0;
    }
    if (a <= n) {
      f[a] = b;
    } else {
      f[b] = a, c[b] = 1;
    }
  }
  suf[n] = f[n];
  for (int i = n - 1; i >= 1; i--) {
    suf[i] = max(suf[i + 1], f[i]);
  }
  int pre = INT_MAX, cst[2] = { 0, 0 }, ans = 0;
  stack<int> st[2];
  for (int i = 1; i <= n; i++) {
    pre = min(pre, f[i]);
    if (st[0].empty() || f[i] < f[st[0].top()]) {
      st[0].push(i), cst[0] += c[i];
    } else if (st[1].empty() || f[i] < f[st[1].top()]) {
      st[1].push(i), cst[1] += c[i];
    } else {
      puts("-1");
      return 0;
    }
    if (pre > suf[i + 1]) {
      ans += min(cst[0] + (int) st[1].size() - cst[1]
               , cst[1] + (int) st[0].size() - cst[0]);
      cst[0] = cst[1] = 0;
      while (!st[0].empty()) st[0].pop();
      while (!st[1].empty()) st[1].pop();
    }
  }
  printf("%d\n", ans);
  return 0;
}