CodeForces - 699D

利用並查集判斷環和樹

第一次兩個節點判斷是,如果不在一個樹上就合併,如果出現兩個點在一個樹上就說明出現了環


#include<iostream>
#include<cstdio>
using namespace std;
const int maxn = 200000 + 10;
int a[maxn], p[maxn];
int tofind(int x){
    if(x == p[x]) return x;
    return p[x] = tofind(p[x]);
}
void join(int x, int y){
    int px = tofind(x);
    int py = tofind(y);
    p[px] = py;

}
int main(){
    int n;
    scanf("%d", &n);
    int root = -1;
    for(int i = 1; i <= n; i++) p[i] = i;
    for(int i = 1; i <= n; i++){
        scanf("%d", &a[i]);
        if(i == a[i])
            root = i;
    }
    int pv, pu;
    int ans = 0;
    for(int i = 1; i <= n; i++){
        if(a[i] != root){
            pu = tofind(i);
            pv = tofind(a[i]);
            if(pu == pv){
                ans++;
                if(root == -1) root = i;
                a[pu] = root;
            }
            else{
                join(i, a[i]);
            }
        }
    }
    printf("%d\n", ans);
    for(int i = 1; i <= n; i++){
        if(i == 1) printf("%d", a[i]);
        else printf(" %d", a[i]);
    }
    printf("\n");
    return 0;
}

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