题解:CF1411C Peaceful Rooks

· · 题解

CF1411C Peaceful Rooks

Solution

并查集:

Code

#include<bits/stdc++.h>
const int N=1e5+5;
int fa[N];
void init(int x)//初始化自己为自己的父亲
{
    for(int i=1;i<=x;i++) fa[i]=i;
    return;
}
int findr(int x)//寻找根
{
    if(fa[x]==x) return x;
    return fa[x]=findr(fa[x]);//类似记忆化
}
void merge(int x,int y)//合并成一个集合
{
    int fx=findr(x);
    int fy=findr(y);
    if(fx==fy) return;
    fa[fy]=fx;
}
int main()
{
    ios::sync_with_stdio(false);//快读
    cin.tie(nullptr);
    cout.tie(nullptr);
    int t;
    cin<<t;
    while(t--)
    {
        int n,m;
        cin>>n>>m;
        memset(fa,0,sizeof fa);//多测要清空
        init(n);
        int ans=m;
        for(int i=1;i<=m;i++)
        {
            int x,y;
            cin>>x>>y;
            if(x==y) ans--;
            else
            {
                if(findr(x)==findr(y)) ans++;//若他们根相同,则需移动步数+1,
                else merge(x,y);//若不同,则合并
            }
        }
        cout<<ans<<endl;
    }
    return;
}