luogu P4012 深海机器人问题
费用流问题,每个样本选一次,就连一条capacity为1,权为给定的值,因为可以重复走,再连capacity为无穷,权为0的边,再一次连接给定的出点和汇点即可
#include<bits/stdc++.h>
using namespace std;
#define lowbit(x) ((x)&(-x))
typedef long long LL;
const int maxm = 3e3+5;
const int INF = 0x3f3f3f3f;
struct edge{
int u, v, cap, flow, cost, nex;
} edges[maxm];
int head[maxm], cur[maxm], cnt, fa[1024], d[1024], p, q;
bool inq[1024];
void init() {
memset(head, -1, sizeof(head));
}
void add(int u, int v, int cap, int cost) {
edges[cnt] = edge{u, v, cap, 0, cost, head[u]};
head[u] = cnt++;
}
void addedge(int u, int v, int cap, int cost) {
add(u, v, cap, cost), add(v, u, 0, -cost);
}
bool spfa(int s, int t, int &flow, LL &cost) {
for(int i = 0; i <= p*q+3; ++i) d[i] = INF; //init()
memset(inq, false, sizeof(inq));
d[s] = 0, inq[s] = true;
fa[s] = -1, cur[s] = INF;
queue<int> q;
q.push(s);
while(!q.empty()) {
int u = q.front();
q.pop();
inq[u] = false;
for(int i = head[u]; i != -1; i = edges[i].nex) {
edge& now = edges[i];
int v = now.v;
if(now.cap > now.flow && d[v] > d[u] + now.cost) {
d[v] = d[u] + now.cost;
fa[v] = i;
cur[v] = min(cur[u], now.cap - now.flow);
if(!inq[v]) {q.push(v); inq[v] = true;}
}
}
}
if(d[t] == INF) return false;
flow += cur[t];
cost += 1LL*d[t]*cur[t];
for(int u = t; u != s; u = edges[fa[u]].u) {
edges[fa[u]].flow += cur[t];
edges[fa[u]^1].flow -= cur[t];
}
return true;
}
int MincostMaxflow(int s, int t, LL &cost) {
cost = 0;
int flow = 0;
while(spfa(s, t, flow, cost));
return flow;
}
void run_case() {
init();
int a, b, val;
cin >> a >> b >> p >> q;
p++, q++;
for(int i = 1; i <= p; ++i)
for(int j = 1; j < q; ++j) {
cin >> val;
addedge((i-1)*q+j, (i-1)*q+j+1, 1, -val);
addedge((i-1)*q+j, (i-1)*q+j+1, INF, 0);
}
for(int i = 1; i <= q; ++i)
for(int j = 1; j < p; ++j) {
cin >> val;
addedge((j-1)*q+i, j*q+i, 1, -val);
addedge((j-1)*q+i, j*q+i, INF, 0);
}
int s = 0, t = p*q+2;
for(int i = 0; i < a; ++i) {
int k, x, y;
cin >> k >> x >> y;
x++, y++;
addedge(s, (x-1)*q+y, k, 0);
}
for(int i = 0; i < b; ++i) {
int k, x, y;
cin >> k >> x >> y;
x++, y++;
addedge((x-1)*q+y, t, k, 0);
}
LL cost = 0;
MincostMaxflow(s, t, cost);
cout << -cost;
}
int main() {
ios::sync_with_stdio(false), cin.tie(0);
run_case();
cout.flush();
return 0;
}