思路1:bfs + 并查集
题意很简单,画个图就知道是求最小环长,利用并查集将v认u为父亲,最终在每个集合里面的根节点都是起始结点。最后走一个bfs或者dfs就能跑出答案。
AC代码
#include<cstdio>
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
#define IOS ios::sync_with_stdio(false)
const int maxn = 200050;
int path[maxn], arr[maxn], fa[maxn];
vector<int> G[maxn];
queue<int> q;
int n;
int find(int x){
return fa[x] == x ? fa[x] : fa[x] = find(fa[x]);
}
void merge(int x, int y){
x = find(x);
y = find(y);
if (x != y){
fa[y] = x;
}
}
int bfs(){
while (!q.empty()) q.pop();
for (int i = 1; i <= n; ++i){
if (fa[i] == i){
q.push(i);
}
}
int res = n + 1;
while (!q.empty()){
int u = q.front(); q.pop();
for (int v : G[u]){
if (path[v]){
res = min(res, path[u] - path[v] + 1);
continue;
}
path[v] = path[u] + 1;
q.push(v);
}
}
return res;
}
void solve(){
int v, cnt = 1;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) fa[i] = i;
for (int i = 1; i <= n; ++i){
scanf("%d", &v);
G[i].push_back(v);
merge(i, v);
}
int ans = bfs();
printf("%d\n", ans);
}
int main(){
solve();
return 0;
}
思路2:Trajan
利用Trajan算法求每个强连通分量结点个数,缩点后找结点个数超过1的就满足条件,取最小值即可。
#include<cstdio>
#include<iostream>
#include<vector>
#include<stack>
#include<cstring>
#include<algorithm>
using namespace std;
#define IOS ios::sync_with_stdio(false)
const int maxn = 200050;
int dfn[maxn], low[maxn], color[maxn], all[maxn], tot, ind;
bool instack[maxn];
vector<int> G[maxn];
stack<int> st;
void tarjan(int u){
dfn[u] = low[u] = ++ind;
st.push(u);
instack[u] = true;
for (int v : G[u]){
if (dfn[v] == 0){
tarjan(v);
low[u] = min(low[u], low[v]);
} else if (instack[v]){
low[u] = min(low[u], dfn[v]);
}
}
if (dfn[u] == low[u]){
int now;
tot++;
do{
now = st.top(); st.pop();
color[now] = tot;
all[tot]++;
instack[now] = false;
}while(now != u);
}
}
void solve(){
int n, v, cnt = 1;
scanf("%d", &n);
for (int i = 1; i <= n; ++i){
scanf("%d", &v);
G[i].push_back(v);
}
for (int i = 1; i <= n; ++i){
if (dfn[i] == 0){
tarjan(i);
}
}
int ans = n;
for (int i = 1; i <= tot; ++i){
if (all[i] > 1){
ans = min(ans, all[i]);
}
}
printf("%d\n", ans);
}
int main(){
solve();
return 0;
}
/**
6
2 4 5 3 6 3
**/