#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=;
int idh[][],idl[][],E[maxn],V[maxn],head[maxn];
char map[][];
bool if_[][];
inline bool bfs()
{
for(int i=s;i<=t;i++) deep[i]=-;
int h=,tail=,now;que[]=s,deep[s]=;
while(h<tail)
{
now=que[h++];
for(int i=head[now];i;i=E[i])
{
if(F[i]&&deep[V[i]]<)
{
deep[V[i]]=deep[now]+;
if(V[i]==t) return true;
que[tail++]=V[i];
}
}
}
return false;
}
inline int flowing(int now,int flow)
{
if(now==t||flow<=) return flow;
int oldflow=,pos;
for(int i=head[now];i;i=E[i])
{
if(F[i]&&deep[V[i]]==deep[now]+)
{
pos=flowing(V[i],min(flow,F[i]));
F[i]-=pos,F[i^]+=pos,oldflow+=pos,flow-=pos;
if(!flow) return oldflow;
}
}
if(!oldflow) deep[now]=-;
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]=,head[v]=cnt;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=;i<=n;i++) scanf("%s",map[i]+);
for(int i=;i<=n;i++)
for(int v=;v<=m;v++)
if(map[i][v]=='*'&&!idh[i][v])
{
toth++;
for(int l=v;l>&&map[i][l]!='#';l--)
{
idh[i][l]=toth;
if(map[i][l]=='x') idh[i][l]=;
}
for(int r=v+;r<=m&&map[i][r]!='#';r++)
{
idh[i][r]=toth;
if(map[i][r]=='x') idh[i][r]=;
}
}
for(int i=;i<=n;i++)
for(int v=;v<=m;v++)
if(map[i][v]=='*'&&!idl[i][v])
{
totl++;
for(int l=i;l>&&map[l][v]!='#';l--)
{
idl[l][v]=totl;
if(map[l][v]=='x') idl[l][v]=;
}
for(int r=i+;r<=n&&map[r][v]!='#';r++)
{
idl[r][v]=totl;
if(map[r][v]=='x') idl[r][v]=;
}
}
for(int i=;i<=n;i++)
for(int v=;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,);
}
s=,t=toth+totl+;
for(int i=;i<=toth;i++) edge_add(s,i,);
for(int i=;i<=totl;i++) edge_add(i+toth,t,);
int ans=;
while(bfs()) ans+=flowing(s,INF);
cout<<ans;
return ;
}
04-23 13:11