标签:des style blog http color java os io
2 2 DK HF 3 3 ADC FJK IHE -1 -1
2 3很坑爹的并查集,输入以字母给出,所以对于每一个字母,都要判断它是否和上下左右的字母连通,如果连通,则将它们合并,最后集合的个数就是答案。很无奈我只好在纸上把和所有相连通的字母找出来然后存在了数组里面。#include <iostream> #include <cstdio> #include <cstring> using namespace std; int m,n,fa[10010],hash[10010]; char ma[60][60]; void Make_set(int n) { for(int i=1;i<=n;i++) fa[i]=i; } int Find(int x) { if(x!=fa[x]) fa[x]=Find(fa[x]); return fa[x]; } void Union(int x,int y) { int fx=Find(x); int fy=Find(y); if(fx==fy) return ; fa[fy]=fx; } int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}}; char ok[11][4][12]={{"CDEHIJK","","BDFGIJK",""},{"CDEHIJK","","","ACFGHIK"},{"","ABEGHJK","BDFGIJK",""},{"","ABEGHJK","","ACFGHIK"},{"CDEHIJK","ABEGHJK","",""},{"","","BDFGIJK","ACFGHIK"},{"CDEHIJK","","BDFGIJK","ACFGHIK"},{"CDEHIJK","ABEGHJK","BDFGIJK",""},{"","ABEGHJK","BDFGIJK","ACFGHIK"},{"CDEHIJK","ABEGHJK","","ACFGHIK"},{"CDEHIJK","ABEGHJK","BDFGIJK","ACFGHIK"}}; void bfs(int x,int y) { int i,tx=x,ty=y; for(i=0;i<4;i++) { tx=x+dir[i][0]; ty=y+dir[i][1]; if(0<=tx&&tx<m&&0<=ty&&ty<n) { int flag=0,len=strlen(ok[ma[x][y]-'A'][i]); for(int j=0;j<len;j++) { if(ok[ma[x][y]-'A'][i][j]==ma[tx][ty]) { flag=1; break; } } if(flag) Union(x*n+y+1,tx*n+ty+1); } } } int main() { int i,j; while(~scanf("%d%d",&m,&n)) { memset(hash,0,sizeof(hash)); if(m==-1&&n==-1) break; for(i=0;i<m;i++) scanf("%s",ma[i]); Make_set(m*n); for(i=0;i<m;i++) for(j=0;j<n;j++) bfs(i,j); for(i=1;i<=m*n;i++) { int f=Find(i); hash[f]++; } int cnt=0; for(i=1;i<=m*n;i++) if(hash[i]) cnt++; printf("%d\n",cnt); } return 0; }
HDU 1198-Farm Irrigation(并查集),布布扣,bubuko.com
标签:des style blog http color java os io
原文地址:http://blog.csdn.net/qq_16255321/article/details/38585751