題目: PolandBall and Forest
思路:本題就是一個簡單的並查集
並查集參考博客:並查集(Disjoint Set Union)
代碼:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e4+10;
int fa[maxn];
int Find(int x){
if(x != fa[x])fa[x] = Find(fa[x]);
return fa[x];
}
int main(){
int n;
scanf("%d", &n);
for(int i = 1; i <= n; i++)fa[i] = i;
for(int i = 1; i <= n; i++){
int v;
scanf("%d", &v);
int fx, fy;
fx = Find(i);
fy = Find(v);
if(fx != fy)fa[fx] = fy;
}
int ans = 0;
for(int i = 1; i <= n; i++){
if(fa[i] == i)ans++;
}
printf("%d\n", ans);
return 0;
}