[题目链接]
[算法]
不难看出这是一棵基环外向森林,运行tarjan算法找出最小环即可
[代码]
#include<bits/stdc++.h> using namespace std; #define MAXN 200010 const int inf = 2e9; struct edge { int to,nxt; } e[MAXN]; int i,n,ans,x,tot,timer,top,cnt; int head[MAXN],size[MAXN],dfn[MAXN],low[MAXN],s[MAXN]; bool visited[MAXN],instack[MAXN]; namespace IO { template <typename T> inline void read(T &x) { int f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; } for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; x *= f; } template <typename T> inline void write(T x) { if (x < 0) { putchar('-'); x = -x; } if (x > 9) write(x / 10); putchar(x % 10 + '0'); } template <typename T> inline void writeln(T x) { write(x); puts(""); } } ; inline void addedge(int u,int v) { tot++; e[tot] = (edge){v,head[u]}; head[u] = tot; } inline void tarjan(int u) { int i,v; dfn[u] = low[u] = ++timer; instack[u] = true; s[++top] = u; for (i = head[u]; i; i = e[i].nxt) { v = e[i].to; if (!dfn[v]) { tarjan(v); low[u] = min(low[u],low[v]); } else if (instack[u]) low[u] = min(low[u],dfn[v]); } if (low[u] == dfn[u]) { cnt++; while (s[top + 1] != u) { size[cnt]++; top--; } } } int main() { IO :: read(n); for (i = 1; i <= n; i++) { IO :: read(x); addedge(i,x); } for (i = 1; i <= n; i++) { if (!dfn[i]) tarjan(i); } ans = inf; for (i = 1; i <= cnt; i++) { if (size[i] > 1) ans = min(ans,size[i]); } IO :: writeln(ans); return 0; }