今天开始(第三轮)并查集,,之前学的忘了一些
本题很简单直接上代码
#include<iostream> #include<cstring> #include<cstdio> #define MAXN 55 using namespace std; int F[MAXN*MAXN]; int find(int x){ if(F[x]==-1) return x; return F[x]=find(F[x]); } void bing(int a,int b){ int t1=find(a); int t2=find(b); if(t1!=t2) F[t1]=t2; } char mp[MAXN][MAXN]; int main(){ int n,m; while(scanf("%d%d",&n,&m)==2 && n>0){ for(int i=0;i<n;i++) for(int j=0;j<m;j++) cin>>mp[i][j]; for(int i=0;i<n*m;i++) F[i]=-1; for(int i=0;i<n;i++) for(int j=0;j<m;j++){//上下联通或者左右联通 if(i>0 && (mp[i][j]=='A'||mp[i][j]=='B'||mp[i][j]=='E'||mp[i][j]=='G'||mp[i][j]=='H'||mp[i][j]=='J'||mp[i][j]=='K')) if(mp[i-1][j]=='C'||mp[i-1][j]=='D'||mp[i-1][j]=='E'||mp[i-1][j]=='H'||mp[i-1][j]=='I'||mp[i-1][j]=='J'||mp[i-1][j]=='K') bing(i*m+j,(i-1)*m+j); if(j>0 && (mp[i][j]=='A'||mp[i][j]=='C'||mp[i][j]=='F'||mp[i][j]=='G'||mp[i][j]=='H'||mp[i][j]=='I'||mp[i][j]=='K')) if(mp[i][j-1]=='B'||mp[i][j-1]=='D'||mp[i][j-1]=='F'||mp[i][j-1]=='G'||mp[i][j-1]=='I'||mp[i][j-1]=='J'||mp[i][j-1]=='K') bing(i*m+j,i*m+j-1); } int ans=0; for(int i=0;i<n*m;i++) if(F[i]==-1) ans++; printf("%d ",ans); } return 0; }