传送门
和方格取数2实际上是一道题
输入非常的恶心,不想多说
#include
using namespace std;
const int maxm=1050;
const int maxn=1050;
const int INF=0x3f3f3f3f;
int s,t,tot,n,m;
int a,b;
struct Edge{
int to,nxt,cap,flow,cost;
}edge[105000];
int Head[maxn],tol;
int mp[maxn][maxn];
int pre[maxn],dis[maxn];
bool vis[maxn];
void addedge2(int u,int v,int cap,int cost){
edge[tol].to=v;
edge[tol].cap=cap;
edge[tol].cost=cost;
edge[tol].flow=0;
edge[tol].nxt=Head[u];
Head[u]=tol++;
}
void addedge(int u,int v,int cap,int cost){
addedge2(u,v,cap,cost);
addedge2(v,u,0,-cost);
}
bool spfa(int s,int t){
queue<int> q;
for(int i=0;ifalse;pre[i]=-1;
}
dis[s]=0;vis[s]=true;
q.push(s);
while(!q.empty()){
int u=q.front();
q.pop();
vis[u]=false;
for(int i=Head[u];i!=-1;i=edge[i].nxt){
int v=edge[i].to;
if (edge[i].cap>edge[i].flow&&dis[v]>dis[u]+edge[i].cost){
dis[v]=dis[u]+edge[i].cost;
pre[v]=i;
if (!vis[v]){
vis[v]=true;
q.push(v);
}
}
}
}
if (pre[t]==-1) return false;
return true;
}
int minCostMaxflow(int s,int t,int &cost){
int flow=0;
cost=0;
while(spfa(s,t)){
int Min=INF;
for(int i=pre[t];i!=-1;i=pre[edge[i^1].to])
if (Min>edge[i].cap-edge[i].flow)
Min=edge[i].cap-edge[i].flow;
for(int i=pre[t];i!=-1;i=pre[edge[i^1].to]){
edge[i].flow+=Min;
edge[i^1].flow-=Min;
cost+=edge[i].cost*Min;
}
flow+=Min;
}
return flow;
}
int main(){
//freopen("input.txt","r",stdin);
while(scanf("%d%d%d%d",&a,&b,&n,&m)!=EOF){
memset(Head,-1,sizeof(Head));
int cost,c=0,x,y;
tol=s=0;
t=(n+1)*(m+1)+1;
tot=t+1;
for(int i=0;i<=n;i++)
for(int j=0;j<=m;j++)
mp[i][j]=++c;
for(int i=0;i<=n;i++)
for(int j=0;jscanf("%d",&c);
addedge(mp[i][j],mp[i][j+1],1,-c);
addedge(mp[i][j],mp[i][j+1],INF,0);
}
for(int j=0;j<=m;j++)
for(int i=0;iscanf("%d",&c);
addedge(mp[i][j],mp[i+1][j],1,-c);
addedge(mp[i][j],mp[i+1][j],INF,0);
}
for(int i=0;iscanf("%d%d%d",&c,&x,&y);
addedge(s,mp[x][y],c,0);
}
for(int i=0;iscanf("%d%d%d",&c,&x,&y);
addedge(mp[x][y],t,c,0);
}
int flow;
flow=minCostMaxflow(s,t,cost);
printf("%d\n",-cost);
}
return 0;
}