題目鏈接
題意:一個奶牛,之間有互相仰慕的關系,如果A仰慕B,B仰慕C,意味著A也仰慕C,問有多少奶牛被所有奶牛仰慕
思路:強連通縮點,點權為連通集合個數,如果出度為0的點個數大於1個,答案就是0,如果等於1個,答案就是那個點的權值
代碼:
#include#include #include #include #include using namespace std; const int N = 10005; int n, m; vector g[N]; int pre[N], dfn[N], dfs_clock, sccn, sccno[N], val[N]; stack S; void dfs_scc(int u) { pre[u] = dfn[u] = ++dfs_clock; S.push(u); for (int i = 0; i < g[u].size(); i++) { int v = g[u][i]; if (!pre[v]) { dfs_scc(v); dfn[u] = min(dfn[u], dfn[v]); } else if (!sccno[v]) dfn[u] = min(dfn[u], pre[v]); } if (dfn[u] == pre[u]) { sccn++; int cnt = 0; while (1) { cnt++; int x = S.top(); S.pop(); sccno[x] = sccn; if (x == u) break; } val[sccn] = cnt; } } void find_scc() { dfs_clock = sccn = 0; memset(pre, 0, sizeof(pre)); memset(sccno, 0, sizeof(sccno)); for (int i = 1; i <= n; i++) if (!pre[i]) dfs_scc(i); } int out[N]; int main() { while (~scanf("%d%d", &n, &m)) { int u, v; while (m--) { scanf("%d%d", &u, &v); g[u].push_back(v); } find_scc(); memset(out, 0, sizeof(out)); for (int i = 1; i <= n; i++) { for (int j = 0; j < g[i].size(); j++) { int v = g[i][j]; if (sccno[i] != sccno[v]) out[sccno[i]]++; } } int cnt = 0, ans; for (int i = 1; i <= sccn; i++) { if (!out[i]) { cnt++; ans = val[i]; } } if (cnt > 1) ans = 0; printf("%d\n", ans); } return 0; }