/* -*- coding: utf-8 -*- * * 2403.cc: No.2403 "Eight" Bridges of Kテカnigsberg - yukicoder */ #include #include #include using namespace std; /* constant */ const int MAX_N = 200000; /* typedef */ using vi = vector; struct UFT { vector links, ranks, sizes; UFT() {} void init(int n) { links.resize(n); for (int i = 0; i < n; i++) links[i] = i; ranks.assign(n, 1); sizes.assign(n, 1); } int root(int i) { int i0 = i; while (links[i0] != i0) i0 = links[i0]; return (links[i] = i0); } int rank(int i) { return ranks[root(i)]; } int size(int i) { return sizes[root(i)]; } bool same(int i, int j) { return root(i) == root(j); } int merge(int i0, int i1) { int r0 = root(i0), r1 = root(i1), mr; if (r0 == r1) return r0; if (ranks[r0] == ranks[r1]) { links[r1] = r0; sizes[r0] += sizes[r1]; ranks[r0]++; mr = r0; } else if (ranks[r0] > ranks[r1]) { links[r1] = r0; sizes[r0] += sizes[r1]; mr = r0; } else { links[r0] = r1; sizes[r1] += sizes[r0]; mr = r1; } return mr; } }; /* global variables */ int dgs[MAX_N], gids[MAX_N], es[MAX_N]; UFT uft; vi gvs[MAX_N]; /* subroutines */ /* main */ int main() { int n, m; scanf("%d%d", &n, &m); uft.init(n); for (int i = 0; i < m; i++) { int u, v; scanf("%d%d", &u, &v); u--, v--; dgs[u]++, dgs[v]--; int ru = uft.root(u), rv = uft.root(v); if (ru != rv) { int r = uft.merge(ru, rv); es[r] = es[ru] + es[rv] + 1; } else es[ru]++; } //for (int i = 0; i < n; i++) printf(" %d", dgs[i]); putchar('\n'); fill(gids, gids + n, -1); int gn = 0, eg = 0; for (int i = 0; i < n; i++) if (uft.root(i) == i) { gids[i] = gn++; if (es[i] > 0) eg++; } for (int i = 0; i < n; i++) gvs[gids[uft.root(i)]].push_back(i); //printf(" gn=%d\n", gn); int sum = eg - 1; for (int gi = 0; gi < gn; gi++) { int dsum = 0; for (auto u: gvs[gi]) { if (dgs[u] > 0) dsum += dgs[u]; //printf(" %d,%d", u, dgs[u]); } //putchar('\n'); sum += max(0, dsum - 1); } printf("%d\n", sum); return 0; }