题目链接:
http://www.luogu.org/problem/show?pid=2661
题解:
这题求最小的单向环。
可因为每个节点初度为1,所以所有的强联通分量都只能是单向环。
所以就是有向图强连通分量的模板题。
#include<iostream> #include<cstdio> #include<vector> #include<stack> #include<algorithm> #include<cstring> using namespace std; const int maxn = 200000 + 10; const int INF = 0x3f3f3f3f; vector<int> G[maxn]; int pre[maxn], lowlink[maxn], sccno[maxn], dfs_clock, scc_cnt; stack<int> S; int n,ans; void dfs(int u) { pre[u] = lowlink[u] = ++dfs_clock; S.push(u); for (int i = 0; i < G[u].size(); i++) { int v = G[u][i]; if (!pre[v]) { dfs(v); lowlink[u] = min(lowlink[u], lowlink[v]); } else if (!sccno[v]) { lowlink[u] = min(lowlink[u], pre[v]); } } if (lowlink[u] == pre[u]) { scc_cnt++; int cnt = 0; for (;;) { cnt++; int x = S.top(); S.pop(); sccno[x] = scc_cnt; if (x == u) break; } if(cnt>1) ans = min(ans, cnt); } } void find_scc(int n) { dfs_clock = scc_cnt = 0; memset(sccno, 0, sizeof(sccno)); memset(pre, 0, sizeof(pre)); for (int i = 0; i < n; i++) if (!pre[i]) dfs(i); //for (int i = 0; i < n; i++) printf("sccno[%d]:%d ", i, sccno[i]); } void init() { for (int i = 0; i < n; i++) G[i].clear(); ans = INF; } int main() { while (scanf("%d", &n) == 1 && n) { init(); for (int i = 0; i < n; i++) { int v; scanf("%d", &v); v--; G[i].push_back(v); } find_scc(n); printf("%d ",ans); } return 0; }