题解
费用流大水题。。
随便连边就好了
毫无细节可言。。
CODE:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int MAX=1<<30;
const int N=105*2;
int n,m;
int st,ed;
struct qt
{
int x,y,z,z1,last;//流量 费用
}s[N*N];int num,last[N];
void init (int x,int y,int z,int z1)
{
num++;
s[num].x=x;s[num].y=y;s[num].z=z;s[num].z1=z1;
s[num].last=last[x];
last[x]=num;
swap(x,y);z=0;z1=-z1;
num++;
s[num].x=x;s[num].y=y;s[num].z=z;s[num].z1=z1;
s[num].last=last[x];
last[x]=num;
}
int from[N];
int f[N];
bool in[N];
bool SPFA ()
{
memset(in,false,sizeof(in));
memset(from,-1,sizeof(from));
memset(f,127,sizeof(f));
queue<int> q;
q.push(st);
f[st]=0;in[st]=true;
while (!q.empty())
{
int x=q.front();q.pop();
for (int u=last[x];u!=-1;u=s[u].last)
{
int y=s[u].y;
if (s[u].z>0&&f[y]>f[x]+s[u].z1)
{
f[y]=f[x]+s[u].z1;
from[y]=u;
if (in[y]==false)
{
in[y]=true;
q.push(y);
}
}
}
in[x]=false;
}
return from[ed]!=-1;
}
int ans=0;
void lalal ()
{
int x=from[ed],t=MAX;
while (x!=-1)
{
t=min(t,s[x].z);
x=from[s[x].x];
}
x=from[ed];
while (x!=-1)
{
ans=ans+t*s[x].z1;
s[x].z-=t;
s[x^1].z+=t;
x=from[s[x].x];
}
return ;
}
int a[N][N];
int k;
int P (int x,int y){return (x-1)*m+y;}
int main()
{
num=1;memset(last,-1,sizeof(last));
scanf("%d%d",&n,&m);
st=n*m*2+1;ed=st+1;
for (int u=1;u<=n;u++)
for (int i=1;i<=m;i++)
{
scanf("%d",&a[u][i]);
init(P(u,i),P(u,i)+n*m,1,a[u][i]);
}
scanf("%d",&k);
for (int u=1;u<=k;u++)
{
int x0,y0,x1,y1;
scanf("%d%d%d%d",&x0,&y0,&x1,&y1);
init(P(x0,y0)+n*m,P(x1,y1),1,0);
init(P(x1,y1)+n*m,P(x0,y0),1,0);
}
int o;
scanf("%d",&o);
for (int u=1;u<=o;u++)
{
int x,y;
scanf("%d%d",&x,&y);
init(st,P(x,y),1,0);
}
for (int u=1;u<=o;u++)
{
int x,y;
scanf("%d%d",&x,&y);
init(P(x,y)+n*m,ed,1,0);
}
while (SPFA()) lalal();
for (int u=last[st];u!=-1;u=s[u].last)
if (s[u].z==1)
{
printf("-1\n");
return 0;
}
printf("%d\n",ans);
return 0;
}