PolandBall and Forest

題目: 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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章