SSL P2415 连通块

目录:

题目:

连通块 题目

题意:

求出每加入一颗棋子,当时的连通块总数

分析:

看到连通块,十分明显就是并查集了,对于此题也没什么特殊的,相当于模版默写

思路:

1.初始化并查集
2.每加入颗棋子,连通块+1
3.当这颗棋子可以减少连通块时,总数-1,且合并
4.输出

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#define k(i,j) (i-1)*n+j
#define LL long long
using namespace std;
inline LL read() {
    LL d=0,f=1;char s=getchar();
    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
    while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();}
    return d*f;
}
int n,m,f[250001],b[501][501],x,i,j,ans,p,q;
const short dx[4]={-1,0,1,0};
const short dy[4]={0,1,0,-1};
int find(int x){return x==f[x]?x:f[x]=find(f[x]);}
void judge(int x,int y){f[find(x)]=find(y);return;}
bool check(int x,int y){return find(x)==find(y);}
int main()
{
    n=read();m=read();
    for(int l=1;l<=n*n;l++) f[l]=l;
    while(m--)
    {
        x=read();i=read();j=read();x++;ans++;
        for(int l=0;l<4;l++)
        {
            p=i+dx[l];q=j+dy[l];
            if(p<1||q<1||p>n||q>n) continue;
            if(b[p][q]!=x) continue;
            if(check(k(p,q),k(i,j))) continue;
            judge(k(p,q),k(i,j));ans--;
        }
        b[i][j]=x;
        printf("%d\n",ans);
    }
    fclose(stdin);
    fclose(stdout);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35786326/article/details/80290969