AtCoder Regular Contest 097D: Equals 题解

我们可以把这种交换规则想象成一张图,有一个 N 个点的图,题目中的 ( x i , y i ) 相当于图中的边
我们可以发现一个连通块内的元素是可以任意互换位置的
所以对于每一个 a [ i ] ,我们只要判断第 i 个格子和第 a [ i ] 个格子是否联通就好,用并查集可以轻松的做到这一点

#include <bits/stdc++.h>
using namespace std;

int n,m;
int a[100048];

namespace DSU
{
    int pre[100048];
    inline void init() {for (register int i=1;i<=n;i++) pre[i]=i;}
    inline int find_anc(int x) {if (pre[x]!=x) pre[x]=find_anc(pre[x]); return pre[x];}
    inline void update(int x,int y) {x=find_anc(x);y=find_anc(y);pre[x]=y;}
}

int main ()
{
    int i,x,y;
    scanf("%d%d",&n,&m);
    for (i=1;i<=n;i++) scanf("%d",&a[i]);
    DSU::init();
    for (i=1;i<=m;i++)
    {
        scanf("%d%d",&x,&y);
        DSU::update(x,y);
    }
    int ans=0;
    for (i=1;i<=n;i++) if (DSU::find_anc(i)==DSU::find_anc(a[i])) ans++;
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/iceprincess_1968/article/details/80310417
今日推荐