import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.stdio;

void main() {
    auto N = readln.chomp.to!int;
    auto A = N.iota.map!(_ => readln.split.map!(x => x.to!int-1).array).array;

    auto R = A.map!(a => a[0]).array;
    auto C = A.map!(a => a[1]).array;
    if (R.sort().uniq.array.length != N|| C.sort().uniq.array.length != N) {
        writeln(-1);
        return;
    }

    auto X = new int[](N);
    auto Y = new int[](N);
    foreach (a; A) X[a[0]] = a[1];
    foreach (a; A) Y[a[1]] = a[0];

    int ans = 0;

    foreach (i; 0..N) {
        if (X[i] == i) continue;
        ans += 1;
        int r1 = i, c1 = X[i], r2 = Y[i], c2 = X[Y[i]];
        X[r1] = c2;
        X[r2] = c1;
        Y[c1] = r2;
        Y[c2] = r1;
    }

    ans.writeln;
}

