题目链接: BZOJ(https://www.lydsy.com/JudgeOnline/problem.php?id=1001) 洛谷(https://www.luogu.org/problem/P4001)
分析: 裸最小割,残余图下最小割=最大流,直接Dinic,注意建图时边的数量要乘以6。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 3;
const int INF = 0x3f3f3f3f;
int head[maxn],layer[maxn],tot=1,n,m;
struct Edge {
int to,w,Next;
}edge[maxn*6];
void add(int x,int y,int z)
{
edge[++tot].to=y,edge[tot].w=z,edge[tot].Next=head[x],head[x]=tot;
edge[++tot].to=x,edge[tot].w=z,edge[tot].Next=head[y],head[y]=tot;
}
bool bfs(int s,int t)
{
for(int i=1;i<=n*m;i++) layer[i]=-1;
layer[s]=0;
queue<int> q;
q.push(s);
while(!q.empty())
{
int x=q.front(),y; q.pop();
for(int i=head[x];i;i=edge[i].Next) {
y=edge[i].to;
if(edge[i].w&&layer[y]==-1)
{
layer[y]=layer[x]+1;
q.push(y);
if(y==t) return true;
}
}
}
return false;
}
int Dinic(int x,int t,int flow)
{
if(x==t) return flow;
int rest=flow,k,y;
for(int i=head[x];i&&rest;i=edge[i].Next) {
y=edge[i].to;
if(edge[i].w&&layer[y]==layer[x]+1)
{
k=Dinic(y,t,min(rest,edge[i].w));
if(!k) layer[y]=-1;
edge[i].w-=k;
edge[i^1].w+=k;
rest-=k;
}
}
return flow-rest;
}
int main()
{
int z;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) for(int j=1;j<m;j++) {
scanf("%d",&z); add((i-1)*m+j,(i-1)*m+j+1,z);
}
for(int i=1;i<n;i++) for(int j=1;j<=m;j++) {
scanf("%d",&z); add((i-1)*m+j,i*m+j,z);
}
for(int i=1;i<n;i++) for(int j=1;j<m;j++) {
scanf("%d",&z); add((i-1)*m+j,i*m+j+1,z);
}
int flow=0,maxflow=0;
while(bfs(1,n*m)) while(flow=Dinic(1,n*m,INF))
maxflow+=flow;
printf("%d",maxflow);
return 0;
} 
京公网安备 11010502036488号