UVA 1515 - Pool construction(最小割)
题目链接 https://cn.vjudge.net/problem/UVA-1515
【题意】
输入一个h行w列的字符矩阵,草地用’#’表示,洞用’.’表示,可以把一个草地换成洞,费用为d,也可以把一个洞换成草地,费用为f,最后要在草地和洞之间修建围栏,单位围栏的费用为b,整个矩阵的边界必须是草地,求最小花费.(2<=w,h<=50,1<=d,f,b<=10000)
【思路】
围栏的作用是把草地和洞隔开,联想到“割”的概念,添加源点S和汇点T,S和所有草地相连,如果是边界草地容量为无穷大,如果是其它草地容量为d,同理把所有洞和T相连,容量为f,最后还要把所有点和相邻的四个点连一条边费用为b,然后计算最小割
#include<bits/stdc++.h>
using namespace std;
const int inf=2e9;
const int maxn=3000;
const int dx[4]={0,1,0,-1};
const int dy[4]={1,0,-1,0};
struct Edge{
int from,to,cap,flow;
Edge(int u,int v,int c,int f):from(u),to(v),cap(c),flow(f){}
};
struct Dinic{
int n,m,s,t;
vector<Edge> edges;
vector<int> g[maxn];
bool vis[maxn];
int d[maxn];
int cur[maxn];
void init(int n){
this->n=n;
for(int i=0;i<=n;i++) g[i].clear();
edges.clear();
}
void add(int from,int to,int cap){
edges.push_back(Edge(from,to,cap,0));
edges.push_back(Edge(to,from,0,0));
m=edges.size();
g[from].push_back(m-2);
g[to].push_back(m-1);
}
bool BFS(){
memset(vis,0,sizeof(vis));
queue<int> que;
que.push(s);
d[s]=0;
vis[s]=1;
while(!que.empty()){
int x=que.front();que.pop();
for(int i=0;i<g[x].size();++i){
Edge& e=edges[g[x][i]];
if(!vis[e.to] && e.cap>e.flow){
vis[e.to]=1;
d[e.to]=d[x]+1;
que.push(e.to);
}
}
}
return vis[t];
}
int DFS(int x,int a){
if(x==t || a==0) return a;
int flow=0,f;
for(int& i=cur[x];i<g[x].size();++i){
Edge& e=edges[g[x][i]];
if(d[x]+1==d[e.to] && (f=DFS(e.to,min(a,e.cap-e.flow)))>0){
e.flow+=f;
edges[g[x][i]^1].flow-=f;
flow+=f;
a-=f;
if(a==0) break;
}
}
return flow;
}
int Maxflow(int s,int t){
this->s=s;this->t=t;
int flow=0;
while(BFS()){
memset(cur,0,sizeof(cur));
flow+=DFS(s,inf);
}
return flow;
}
};
Dinic dinic;
int w,h;
int d,f,b;
char g[55][55];
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&w,&h);
scanf("%d%d%d",&d,&f,&b);
for(int i=1;i<=h;++i){
scanf("%s",g[i]+1);
}
int ans=0;
for(int i=1;i<=h;++i){
if(g[i][1]=='.'){
ans+=f;
g[i][1]='#';
}
if(g[i][w]=='.'){
ans+=f;
g[i][w]='#';
}
}
for(int j=1;j<=w;++j){
if(g[1][j]=='.'){
ans+=f;
g[1][j]='#';
}
if(g[h][j]=='.'){
ans+=f;
g[h][j]='#';
}
}
dinic.init(h*w+2);
for(int i=1;i<=h;++i){
for(int j=1;j<=w;++j){
int id=(i-1)*w+j;
if(g[i][j]=='#'){
if(i==1 || i==h || j==1 || j==w) dinic.add(0,id,inf);
else dinic.add(0,id,d);
}
else dinic.add(id,h*w+1,f);
for(int k=0;k<4;++k){
int x=dx[k]+i;
int y=dy[k]+j;
if(x>=1 && x<=h && y>=1 && y<=w){
int newid=(x-1)*w+y;
dinic.add(id,newid,b);
}
}
}
}
ans+=dinic.Maxflow(0,w*h+1);
printf("%d\n",ans);
}
return 0;
}