标签:style blog http color io os ar for sp
题意:一个奶牛,之间有互相仰慕的关系,如果A仰慕B,B仰慕C,意味着A也仰慕C,问有多少奶牛被所有奶牛仰慕
思路:强连通缩点,点权为连通集合个数,如果出度为0的点个数大于1个,答案就是0,如果等于1个,答案就是那个点的权值
代码:
#include <cstdio> #include <cstring> #include <vector> #include <algorithm> #include <stack> using namespace std; const int N = 10005; int n, m; vector<int> g[N]; int pre[N], dfn[N], dfs_clock, sccn, sccno[N], val[N]; stack<int> 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; }
标签:style blog http color io os ar for sp
原文地址:http://blog.csdn.net/accelerator_/article/details/40304713