AtCoder Regular Contest 074 F - Lotus Leaves
题目传送门:https://arc074.contest.atcoder.jp/tasks/arc074_d
题目大意:
给定一个\(H×W\)的网格图,o
是可以踩踏的点,.
是不可踩踏的点。
现有一人在S
处,向T
移动,若此人现在在\((i,j)\)上,那么下一步他可以移动到\((i,k)\)或\((k,j)\)上,\(k\)任意
问最少需要将多少个o
改成.
,可以使这个人无法从S
到达T
,输出最少需要更改的数目;如果无论如何都不能使这个人无法从S
到T
,则输出\(-1\)
这个模型就是最小割啊……我们对于每个点拆点,然后对于所有o
,入点向出点连一条流量为1的边,S
和T
的话,入点向出点连一条流量为\(\infty\)的边;对于移动,我们由某个点的出点向其能到达的入点连一条流量为\(\infty\)的边,直接最小割即可
/*program from Wolfycz*/
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define inf 0x7f7f7f7f
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
inline char gc(){
static char buf[1000000],*p1=buf,*p2=buf;
return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;
}
inline int frd(){
int x=0,f=1; char ch=gc();
for (;ch<'0'||ch>'9';ch=gc()) if (ch=='-') f=-1;
for (;ch>='0'&&ch<='9';ch=gc()) x=(x<<3)+(x<<1)+ch-'0';
return x*f;
}
inline int read(){
int x=0,f=1; char ch=getchar();
for (;ch<'0'||ch>'9';ch=getchar()) if (ch=='-') f=-1;
for (;ch>='0'&&ch<='9';ch=getchar()) x=(x<<3)+(x<<1)+ch-'0';
return x*f;
}
inline void print(int x){
if (x<0) putchar('-'),x=-x;
if (x>9) print(x/10);
putchar(x%10+'0');
}
const int N=1e2,M=6e6;
char map[N+10][N+10];
int pre[M+10],now[N*N*2+10],child[M+10],val[M+10];
int h[N*N*2+10],deep[N*N*2+10];
bool vis[N*N*2+10];
int n,m,S,T,tot=1;
int Get(int x,int y){return (x-1)*m+y;}
void join(int x,int y,int z){pre[++tot]=now[x],now[x]=tot,child[tot]=y,val[tot]=z;}
void insert(int x,int y,int z){join(x,y,z),join(y,x,0);}
bool bfs(int x){
int head=1,tail=1;
memset(deep,255,sizeof(deep));
deep[h[1]=x]=0;
for (;head<=tail;head++){
int Now=h[head];
for (int p=now[Now],son=child[p];p;p=pre[p],son=child[p]){
if (!~deep[son]&&val[p]){
deep[h[++tail]=son]=deep[Now]+1;
if (son==T) return 1;
}
}
}
return 0;
}
int dfs(int x,int v){
if (x==T) return v;
int res=0;
for (int p=now[x],son=child[p];p;p=pre[p],son=child[p]){
if (deep[son]>deep[x]&&val[p]){
int k=dfs(son,min(v,val[p]));
val[p]-=k,v-=k;
val[p^1]+=k,res+=k;
if (!v) break;
}
}
if (!res) deep[x]=-1;
return res;
}
int main(){
n=read(),m=read(),S=2*n*m+1,T=S+1;
for (int i=1;i<=n;i++){
scanf("%s",map[i]+1);
for (int j=1;j<=m;j++){
if (map[i][j]=='.') continue;
if (map[i][j]!='o'){
insert(Get(i,j),Get(i,j)+n*m,inf);
if (map[i][j]=='S') insert(S,Get(i,j),inf);
if (map[i][j]=='T') insert(Get(i,j)+n*m,T,inf);
map[i][j]='o';
}else insert(Get(i,j),Get(i,j)+n*m,1);
}
}
for (int i=1;i<=n;i++){
for (int j=1;j<=m;j++){
if (map[i][j]=='o'){
for (int k=1;k<=n;k++) if (map[k][j]=='o'&&k!=i) insert(Get(i,j)+n*m,Get(k,j),inf);
for (int k=1;k<=m;k++) if (map[i][k]=='o'&&k!=j) insert(Get(i,j)+n*m,Get(i,k),inf);
}
}
}
int Ans=0;
while (bfs(S)) Ans+=dfs(S,inf);
printf(Ans>=inf?"-1\n":"%d\n",Ans);
return 0;
}