bzoj1529: [POI2005]ska Piggy banks(並查集)

Hanks_o發表於2018-04-16

題目傳送門

解法:
據說叫什麼外向樹。
https://wenku.baidu.com/view/820697649b89680202d82527.html

程式碼實現:

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cmath>
using namespace std;
int fa[1100000];int findfa(int x) {if(fa[x]!=x) fa[x]=findfa(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 x;scanf("%d",&x);
        int xx=findfa(x),yy=findfa(i);
        if(xx!=yy)fa[xx]=yy;
    }
    int ans=0;for(int i=1;i<=n;i++)if(fa[i]==i)ans++;
    printf("%d\n",ans);
    return 0;
}

相關文章