HDU 1198 Farm Irrigation

题目大意:给你地图,让你判断需要多少水才可以将农场灌满。

题解:显然用并查集比较容易,将可以连通的并起来,最后输出连通块的数目即可,一开始我用字母分类讨论发现很麻烦,于是参考别人的博客发现,直接自己写一个矩阵,然后处理一下读入数据会比较简单:

#include <cstring>   
#include <cstdio>   
#include <iostream>  
using namespace std;  
int R[11][11]={{0,0,0,0,0,0,0,0,0,0,0},  
{1,0,1,0,0,1,1,1,1,0,1},{0,0,0,0,0,0,0,0,0,0,0},  
{1,0,1,0,0,1,1,1,1,0,1},{0,0,0,0,0,0,0,0,0,0,0},  
{1,0,1,0,0,1,1,1,1,0,1},{1,0,1,0,0,1,1,1,1,0,1},  
{0,0,0,0,0,0,0,0,0,0,0},{1,0,1,0,0,1,1,1,1,0,1},  
{1,0,1,0,0,1,1,1,1,0,1},{1,0,1,0,0,1,1,1,1,0,1}};  
int U[11][11]={{0,0,0,0,0,0,0,0,0,0,0},  
{0,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,0,1,1,0,1,1},  
{1,1,0,0,1,0,1,1,0,1,1},{1,1,0,0,1,0,1,1,0,1,1},  
{0,0,0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0},  
{1,1,0,0,1,0,1,1,0,1,1},{1,1,0,0,1,0,1,1,0,1,1},  
{1,1,0,0,1,0,1,1,0,1,1},{1,1,0,0,1,0,1,1,0,1,1}};  
string map[55]; 
int f[3000];  
void init(int n)  
{  
    int i;  
    for(i=0;i<=n;i++)  
        f[i]=i;  
}  

int sf(int i)  
{  
    int j=i;  
    while(j!=f[j])  
    {  
        j=f[j];  
    }  
    return f[i]=j;  
}  

int Union(int x,int y)  
{  
    x=sf(x);  
    y=sf(y);  
    if(x==y)  
        return 0;  
    else  
    {  
        f[x]=y;  
        return 1;  
    }  
}  
 
int main()  
{  
    int n,m;  
    while(scanf("%d%d",&m,&n),m!=-1&&n!=-1)  
    {  
        int i,j;  
        init(n*m);  
        for(i=0;i<m;i++)  
            cin>>map[i];  
        for(i=0;i<m;i++)  
            for(j=1;j<n;j++)  
                if(R[map[i][j-1]-'A'][map[i][j]-'A'])  
                    Union(i*n+j-1,i*n+j);  
        for(i=0;i<n;i++)  
            for(j=1;j<m;j++)  
                if(U[map[j-1][i]-'A'][map[j][i]-'A'])  
                    Union((j-1)*n+i,j*n+i);  
        int count=0;  
        for(i=0;i<n*m;i++)  
        {  
            if(f[i]==i)  
                count++;  
        }  
        printf("%d\n",count);  
    }  
    return 0;  
}  
posted @ 2014-02-14 11:54  forever97  阅读(180)  评论(0编辑  收藏  举报