HDU 1198 Farm Irrigation 并查集

题目连接 : http://acm.hdu.edu.cn/showproblem.php?pid=1198


#include<stdio.h>
#include<string>
#include<cstring>
#include<queue>
#include<algorithm>
#include<functional>
#include<vector>
#include<iomanip>
#include<math.h>
#include<iostream>
#include<sstream>
#include<stack>
#include<set>
#include<bitset>
#include<map>
using namespace std;
const int MAX = 550;
//左上右下
const int type[11][4]= {{1,1,0,0},{0,1,1,0},
                                   {1,0,0,1},{0,0,1,1},
                                   {0,1,0,1},{1,0,1,0},
                                   {1,1,1,0},{1,1,0,1},
                                   {1,0,1,1},{0,1,1,1},
                                   {1,1,1,1}};
const bool VERTICAL = true;
int pre[MAX*MAX+1],cnt,m,n; //转化为一维标号
char farm[MAX][MAX];
void init(int n)
{
    int i;
    for(i=1; i<=n; ++i)
    {
        pre[i] = i;
    }
    cnt = n;
}

int root(int x)
{
    if(x!=pre[x])
    {
        pre[x] = root(pre[x]);
    }
    return pre[x];
}

void merge(int ax,int ay,int bx,int by,bool dir)
{
    if(bx>n || by>m)return;
    bool mark = false;
    int ta,tb;

    ta = farm[ax][ay]-'A';
    tb = farm[bx][by]-'A';

    if(dir)
    {
        if(type[ta][3] && type[tb][1])mark = true;
    }
    else
    {
        if(type[ta][2] && type[tb][0])mark = true;
    }

    if(mark)
    {
        int fx = root((ax-1)*m+ay);
        int fy = root((bx-1)*m+by);
        if(fx!=fy)
        {
            pre[fy] = fx;
            --cnt;
        }
    }
}


int main()
{
    int i,j;
    while(scanf("%d %d",&n,&m)!=EOF)
    {
        if(n==-1 && m==-1)break;
        init(n*m);
        for(i=1; i<=n; ++i)
        {
            scanf("%s",farm[i]+1);
        }
        for(i=1; i<=n; ++i)
        {
            for(j=1; j<=m; ++j)
            {
                merge(i,j,i+1,j,VERTICAL);
                merge(i,j,i,j+1,!VERTICAL);
            }
        }
        printf("%d\n",cnt);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值