题意:
输入一个h行w列的字符矩阵,‘#’表示草地,‘.’表示洞。可以把草改成洞,花费为d;也可以把洞填成草,花费为f。最后还要在草和洞之间修围栏,每条边的围栏花费为b。矩阵第一行/列和最后一行/列必须是草,求最小花费。2<=w,h<=50,1<=d,f,b<=10000。
思路:
把草放在一列,把洞放在一列,相邻的节点连在一起,砍断每一条边的费用是b,引入源点s和汇点t,s连接所有的草,砍断每条边的费用是d,由于题目要求最外圈的草不能改成洞,所以s到这些草的费用是正无穷,t连接所有的洞,砍断每条边的费用是f;隔断s和t的最小割就是问题的答案。
代码:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
typedef long long ll;
using namespace std;
const int N = 55;
const int maxn = 3000;
const int INF = 0x3f3f3f3f;
struct Edge {
int u, v, c, f;
};
int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
struct Dinic { //最大流模版
int n, m, s, t;
int d[maxn], cur[maxn], vis[maxn];
vector<Edge> edges;
vector<int> G[maxn];
void init(int n) {
this -> n = n;
for(int i=0; i<=n; i++)
G[i].clear();
edges.clear();
}
void Addedge(int u, int v, int c) {
edges.push_back((Edge){u, v, c, 0});
edges.push_back((Edge){v, u, 0, 0});
int m = edges.size();
G[u].push_back(m-2);
G[v].push_back(m-1);
}
bool BFS() {
memset(vis, 0, sizeof(vis));
queue<int> q;
vis[s] = 1; d[s] = 0;
q.push(s);
while(!q.empty()) {
int x = q.front(); q.pop();
for(int i=0; i<G[x].size(); i++) {
auto &e = edges[G[x][i]];
if(!vis[e.v] && e.c > e.f) {
d[e.v] = d[x] + 1;
vis[e.v] = 1;
q.push(e.v);
}
}
}
return vis[t];
}
int DFS(int x, int a) {
if(x == t || a == 0)
return a;
int f, flow = 0;
for(int &i=cur[x]; i<G[x].size(); i++) {
auto &e = edges[G[x][i]];
if(d[e.v] == d[x] + 1 && (f = (DFS(e.v, min(e.c - e.f, a)))) > 0) {
flow += f;
a -= f;
e.f += f;
edges[G[x][i]^1].f -= 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 g;
int main() {
int t, w, h, d, f, b;
cin>>t;
while(t--) {
cin>>w>>h>>d>>f>>b;
char c[N][N];
for(int i=1; i<=h; i++)
cin>>(c[i]+1);
int ans = 0;
//将最外圈的洞填成草
for(int i=1; i<=w; i++) {
if(c[1][i] == '.') {
ans += f;
c[1][i] = '#';
}
if(c[h][i] == '.') {
ans += f;
c[h][i] = '#';
}
}
for(int i=2; i<h; i++) {
if(c[i][1] == '.') {
ans += f;
c[i][1] = '#';
}
if(c[i][w] == '.') {
ans += f;
c[i][w] = '#';
}
}
int t = w * h + 1;
g.init(t);
for(int i=1; i<=h; i++) {
for(int j=1; j<=w; j++) {
int id1 = (i - 1) * w + j;
if(c[i][j] == '#' && (i == 1 || j == 1 || i == h || j == w))
g.Addedge(0, id1, INF); //s到最外圈的草加边
else if(c[i][j] == '#' && i != 1 && j != 1 && i != h && j != w)
g.Addedge(0, id1, d); //s到内圈的草加边
else
g.Addedge(id1, t, f); //t到洞加边
for(int k=0; k<4; k++) {
int x = i + dx[k], y = j + dy[k];
if(x >= 1 && x <= h && y >= 1 && y <= w) {
int id2 = (x - 1) * w + y;
g.Addedge(id1, id2, b); //相邻的节点加边
}
}
}
}
ans += g.MaxFlow(0, t);
cout<<ans<<endl;
}
}