http://poj.org/problem?id=3020

 

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>

using namespace std;

struct node
{
    int x,y;
}pre[50][15];

int b[4]={0,1,-1,0};
int a[4]={1,0,0,-1};
bool had[50][15];
bool map[50][15];  //true ´ú±í *
bool cover[50][15];
bool find(int i,int j)
{
    int I,J;
    for(int l=0;l<4;l++)
    {
        I=i+a[l];
        J=j+b[l];
        if(map[I][J]==true&&!had[I][J])
        {
            had[I][J]=true;
            if(!cover[I][J]||(find(pre[I][J].x,pre[I][J].y)))
            {
                pre[I][J].x=i;
                pre[I][J].y=j;
                pre[i][j].x=I;
                pre[i][j].y=J;
                cover[I][J]=true;
                return true;
            }
        }
    }
    return false;
}
int main()
{
    //freopen("date.txt" ,"r",stdin);
    int n,h,w;
    int i,j;
    char ctemp;
    int ans;
    cin>>n;
    while(n--)
    {
        cin>>h>>w;
        ans=0;
        memset(map,false,sizeof(map));
        for(i=1;i<=h;++i)
        {
            for(j=1;j<=w;++j)
            {
                cin>>ctemp;
                if(ctemp=='*')
                {
                    map[i][j]=true;
                    ++ans;
                }
            }
        }
        memset(pre,0,sizeof(pre));

        memset(cover,false,sizeof(cover));
        for(i=1;i<=h;++i)
        {
            for(j=1;j<=w;++j)
            {
                if(map[i][j]&&!cover[i][j])
                {
                    cover[i][j]=true;
                    memset(had,false,sizeof(had));
                    had[i][j]=true;
                    if(find(i,j))
                    {
                        --ans;
                    }
                   /* for(int x=1;x<=h;x++)
                    {
                        for(int y=1;y<=w;y++)
                        {
                            cout<<"("<<pre[x][y].x<<" "<<pre[x][y].y<<")";
                        }
                        cout<<endl;
                    }
                    cout<<endl;*/
                }
            }
        }
        cout<<ans<<endl;
    }

    return 0;
}

posted on 2012-03-22 13:11  夜->  阅读(144)  评论(0编辑  收藏  举报