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; void main() { auto N = readln.chomp.to!int; auto A = iota(N).map!(_ => readln.split.map!(to!int).array).array; auto X = new int[](2*10^^5+10); auto Y = new int[](2*10^^5+10); foreach (a; A) X[a[0]]++; foreach (a; A) Y[a[1]]++; int indeg = 0; int outdeg = 0; foreach (i; 0..2*10^^5+10) { auto diff = X[i] - Y[i]; if (abs(diff) >= 2) { writeln(0); return; } if (diff == 1) { indeg += 1; } else if (diff == -1) { outdeg += 1; } } if (indeg == 1 && outdeg == 1) { writeln(1); return; } if (indeg == 0 && outdeg == 0) { auto uf = new UnionFind(N); int[int] dict_in; int[int] dict_out; foreach (i, a; A) { if (a[0] in dict_out) { uf.unite(i.to!int, dict_out[a[0]]); } if (a[1] in dict_in) { uf.unite(i.to!int, dict_in[a[1]]); } dict_in[a[0]] = i.to!int; dict_out[a[1]] = i.to!int; } if (uf.table[uf.find(0)] == -N) { writeln(dict_in.keys.length); return; } writeln(0); return; } writeln(0); return; } class UnionFind { import std.algorithm : swap; int n; int[] table; this(int n) { this.n = n; table = new int[](n); table[] = -1; } int find(int x) { return table[x] < 0 ? x : (table[x] = find(table[x])); } void unite(int x, int y) { x = find(x); y = find(y); if (x == y) return; if (table[x] > table[y]) swap(x, y); table[x] += table[y]; table[y] = x; } bool same(int x, int y) { return find(x) == find(y); } }