AC日记——#2057. 「TJOI / HEOI2016」游戏 LOJ

#2057. 「TJOI / HEOI2016」游戏

 

思路:

  最大流;

 

代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define INF 0x3f3f3f3f
#define maxn 2000005
int n,m,s,t,que[maxn],deep[maxn],toth,totl,F[maxn],cnt=1;
int idh[55][55],idl[55][55],E[maxn],V[maxn],head[maxn];
char map[55][55];
bool if_[500][500];
inline bool bfs()
{
    for(int i=s;i<=t;i++) deep[i]=-1;
    int h=0,tail=1,now;que[0]=s,deep[s]=0;
    while(h<tail)
    {
        now=que[h++];
        for(int i=head[now];i;i=E[i])
        {
            if(F[i]&&deep[V[i]]<0)
            {
                deep[V[i]]=deep[now]+1;
                if(V[i]==t) return true;
                que[tail++]=V[i];
            }
        }
    }
    return false;
}
inline int flowing(int now,int flow)
{
    if(now==t||flow<=0) return flow;
    int oldflow=0,pos;
    for(int i=head[now];i;i=E[i])
    {
        if(F[i]&&deep[V[i]]==deep[now]+1)
        {
            pos=flowing(V[i],min(flow,F[i]));
            F[i]-=pos,F[i^1]+=pos,oldflow+=pos,flow-=pos;
            if(!flow) return oldflow;
        }
    }
    if(!oldflow) deep[now]=-1;
    return oldflow;
}
inline void edge_add(int u,int v,int f)
{
    E[++cnt]=head[u],V[cnt]=v,F[cnt]=f,head[u]=cnt;
    E[++cnt]=head[v],V[cnt]=u,F[cnt]=0,head[v]=cnt;
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++) scanf("%s",map[i]+1);
    for(int i=1;i<=n;i++)
        for(int v=1;v<=m;v++)
            if(map[i][v]=='*'&&!idh[i][v])
            {
                toth++;
                for(int l=v;l>0&&map[i][l]!='#';l--)
                {
                    idh[i][l]=toth;
                    if(map[i][l]=='x') idh[i][l]=0;
                }
                for(int r=v+1;r<=m&&map[i][r]!='#';r++)
                {
                    idh[i][r]=toth;
                    if(map[i][r]=='x') idh[i][r]=0;
                }
            }
    for(int i=1;i<=n;i++)
        for(int v=1;v<=m;v++)
            if(map[i][v]=='*'&&!idl[i][v])
            {
                totl++;
                for(int l=i;l>0&&map[l][v]!='#';l--)
                {
                    idl[l][v]=totl;
                    if(map[l][v]=='x') idl[l][v]=0;
                }
                for(int r=i+1;r<=n&&map[r][v]!='#';r++)
                {
                    idl[r][v]=totl;
                    if(map[r][v]=='x') idl[r][v]=0;
                }
            }
    for(int i=1;i<=n;i++)
        for(int v=1;v<=m;v++)
            if(idh[i][v]&&idl[i][v]&&!if_[idh[i][v]][idl[i][v]])
            {
                if_[idh[i][v]][idl[i][v]]=true;
                edge_add(idh[i][v],idl[i][v]+toth,1);
            }
    s=0,t=toth+totl+1;
    for(int i=1;i<=toth;i++) edge_add(s,i,1);
    for(int i=1;i<=totl;i++) edge_add(i+toth,t,1);
    int ans=0;
    while(bfs()) ans+=flowing(s,INF);
    cout<<ans;
    return 0;
}

 

posted @ 2017-07-23 19:01  IIIIIIIIIU  阅读(260)  评论(0编辑  收藏  举报