NOIP2015提高組day1 —— 資訊傳遞(message)
阿新 • • 發佈:2019-02-13
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("message.in");
ofstream fout("message.out");
const int MAX_n = 200000;
int ancestor[MAX_n], transfer[MAX_n];
int union_find(int root) {
if (ancestor[root] == root)
return root;
else
return ancestor[root] = union_find(ancestor[root]);
}
int depth(int initial, int root) {
int sum = 1;
for (int i = initial; i != root; i = transfer[i])
sum++;
return sum;
}
int main() {
int n;
fin >> n;
for (int i = 0; i < n; i++)
ancestor[i] = transfer[i] = i;
int ans = n;
for (int i = 0; i < n; i++) {
fin >> transfer[i];
int roots = union_find(transfer[i]);
if (i != roots)
ancestor[i] = roots;
else
ans = min(ans, depth(transfer[i], i));
}
fout << ans << endl;
return 0;
}