P2661 [NOIP2015 提高组] 信息传递 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
题目是求最小的环,同时注意每一轮不能直接合并,必须等该轮结束再合并。有环则取最小值。
#include<bits/stdc++.h>
#pragma warning (disable:4996);
#define ll long long
#define int ll
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int N = 2e5 + 10;
int n,m, k, q, T;
int a, b, c;
int nx[N];
int pre[N];
int cnt = 0;
int mn = INT_MAX;
int fnd(int a) {
cnt++;
return pre[a] == a ? a : fnd(pre[a]);//没有压缩
}
signed main() {
std::ios::sync_with_stdio(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("out.txt", "w", stdout);
#endif
cin >> n;
for (int j = 1; j <= n; j++)pre[j]=j;
for (int j = 1; j <= n; j++) {
cnt = 0;
cin >> nx[j];
if (fnd(nx[j]) == j)
mn = min(mn, cnt);
else
pre[j] = nx[j];
}
cout << mn << endl;
}