其实仔细想想,这道题和一开始的一道问题很想像,这道题都是边权,就不用拆点了
1.源点像每个可以发个机器人的地方连一条边,容量为可以放的个数,所有回收点向汇点连一条边,容量是可以返回的个数。费用都是0;
2.然后按照方向连点,容量1,费用为该边权值,代表这条边的资源只能采集一次。但是还需要一条容量INF,费用0的边,代表这条边可以通过,但是不一定要采集资源。
之后跑一个最大费用流
#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
#define ss 9999
#define tt 10000
using namespace std;
const int MAXN = 100000;
const int MAXM = 100000;
const int INF = 0x3f3f3f3f;
struct Edge
{
int to,next,cap,flow,cost;
} edge[MAXM];
int head[MAXN],tol;
int pre[MAXN],dis[MAXN];
bool vis[MAXN];
int N;//节点总个数,节点编号从0~N-1
void init(int n)
{
N = n;
tol = 0;
memset(head,-1,sizeof(head));
}
void addedge(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].next = head[u];
head[u] = tol++;
edge[tol].to = u;
edge[tol].cap = 0;
edge[tol].cost = -cost;
edge[tol].flow = 0;
edge[tol].next = head[v];
head[v] = tol++;
}
bool spfa(int s,int t)
{
queue<int>q;
for(int i = 0; i < N; i++)
{
dis[i] = INF;
vis[i] = false;
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].next)
{
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;
else
return true;
}
//返回的是最大流,cost存的是最小费用
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 a,b,p,q;
int rid(int x,int y) {return x*(q + 1) + y;}
int main()
{
scanf("%d%d%d%d",&a,&b,&p,&q);
init(tt+1);
for(int i = 1;i<=p+1;i++)
{
for(int j = 1;j<=q;j++)
{
int x;
scanf("%d",&x);
addedge(rid(i-1,j-1),rid(i-1,j),1,-x);
addedge(rid(i-1,j-1),rid(i-1,j),INF,0);
}
}
for(int i = 1;i<=q+1;i++)
{
for(int j = 1;j<=p;j++)
{
int x;
scanf("%d",&x);
addedge(rid(j-1,i-1),rid(j,i-1),1,-x);
addedge(rid(j-1,i-1),rid(j,i-1),INF,0);
}
}
for(int i = 0;i<a;i++)
{
int k,x,y;
scanf("%d%d%d",&k,&x,&y);
addedge(ss,rid(x,y),k,0);
}
for(int j = 0;j<b;j++)
{
int k,x,y;
scanf("%d%d%d",&k,&x,&y);
addedge(rid(x,y),tt,k,0);
}
int cost = 0;
minCostMaxflow(ss,tt,cost);
printf("%d",-cost);
return 0;
}