平面图转对偶图以最短路得最小割。
注意写spfa的时候要把vis[head]=false写在循环的最后面。
要不然就会WA整整一天。
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#define maxv 1005
#define maxe 6000050
using namespace std;
struct edge
{
int v,w,nxt;
}e[maxe];
int n,m,tmp,dis[maxv*maxv*2+50],nume=0,g[maxv*maxv*2+50],s,t;
bool vis[maxv*maxv*2+50];
queue <int> q;
void addedge(int u,int v,int w)
{
e[++nume].v=v;
e[nume].w=w;
e[nume].nxt=g[u];
g[u]=nume;
e[++nume].v=u;
e[nume].w=w;
e[nume].nxt=g[v];
g[v]=nume;
}
void spfa()
{
while (!q.empty())
q.pop();
q.push(s);
vis[s]=true;
memset(dis,0x3f,sizeof(dis));
dis[s]=0;
while (!q.empty())
{
int head=q.front();
q.pop();
for (int i=g[head];i;i=e[i].nxt)
{
int v=e[i].v;
if (dis[v]>dis[head]+e[i].w)
{
dis[v]=dis[head]+e[i].w;
if (vis[v]==false)
{
vis[v]=true;
q.push(v);
}
}
}
vis[head]=false;
}
}
int main()
{
freopen("cin.in","r",stdin);
freopen("a.out","w",stdout);
memset(g,0,sizeof(g));
scanf("%d%d",&n,&m);
int minn=99999999;
s=0;t=(n-1)*(m-1)*2+1;
for (int i=1;i<=n;i++)
for (int j=1;j<=m-1;j++)
{
scanf("%d",&tmp);
minn=min(minn,tmp);
if (i==1) addedge(s,j*2,tmp);
else if (i==n) addedge((i-2)*(m-1)*2+(j-1)*2+1,t,tmp);
else addedge((i-2)*(m-1)*2+(j-1)*2+1,(i-1)*(m-1)*2+j*2,tmp);
}
for (int i=1;i<=n-1;i++)
for (int j=1;j<=m;j++)
{
scanf("%d",&tmp);
minn=min(minn,tmp);
if (j==1) addedge((i-1)*(m-1)*2+1,t,tmp);
else if (j==m) addedge(s,i*(m-1)*2,tmp);
else addedge((i-1)*(m-1)*2+(j-1)*2,(i-1)*(m-1)*2+(j-1)*2+1,tmp);
}
for (int i=1;i<=n-1;i++)
for (int j=1;j<=m-1;j++)
{
scanf("%d",&tmp);
minn=min(minn,tmp);
addedge((i-1)*(m-1)*2+(j-1)*2+1,(i-1)*(m-1)*2+(j-1)*2+2,tmp);
}
if ((n==1) && (m==1)) {printf("0\n");return 0;}
if ((n==1) || (m==1)) {printf("%d\n",minn);return 0;}
spfa();
printf("%d\n",dis[t]);
return 0;
}