题目链接
题意
P*Q的网格中,给出每条边的收益,若干个机器人的起始位置和目的地。机器人只能往东或北走,每条边可以走多次,但只能算一次收益,求最优机器人移动方案下的最大收益。
思路
有机器人数量,边的收益,这种问题显然优先考虑最大费用最大流。一条边的收益只能记一次,连一条容量为1费用为权值的边;然后每条边收益只记一次,但多个机器人可以走同一条路,所以对于每条边,加一条容量为INF,费用为0的边。建立超级源点S和超级汇点T,S连所有点起始位置点,容量为机器人数量,费用为0,所有目的地点连T,容量为机器人数量费用为0。然后跑最大费用最大流,这里的模板是最小费用最大流,但把所有边的费用改为负值就可以求最大费用了。
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
const int N = 5e3 + 7;
const int M = 1e4 + 7;
const int maxn = 1e3 + 7;
typedef long long ll;
int maxflow, mincost;
struct Edge {
int from, to, cap, flow, cost;
Edge(int u, int v, int ca, int f, int co):from(u), to(v), cap(ca), flow(f), cost(co){};
};
struct MCMF
{
int n, m, s, t;
vector<Edge> edges;
vector<int> G[N];
int inq[N], d[N], p[N], a[N];//是否在队列 距离 上一条弧 可改进量
void init(int n) {
this->n = n;
for (int i = 0; i < n; i++) G[i].clear();
edges.clear();
}
void add(int from, int to, int cap, int cost) {
edges.push_back(Edge(from, to, cap, 0, cost));
edges.push_back(Edge(to, from, 0, 0, -cost));
int m = edges.size();
G[from].push_back(m - 2);
G[to].push_back(m - 1);
}
bool SPFA(int s, int t, int &flow, int &cost) {
for (int i = 0; i < N; i++) d[i] = INF;
memset(inq, 0, sizeof(inq));
d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = INF;
queue<int> que;
que.push(s);
while (!que.empty()) {
int u = que.front();
que.pop();
inq[u]--;
for (int i = 0; i < G[u].size(); i++) {
Edge& e = edges[G[u][i]];
if(e.cap > e.flow && d[e.to] > d[u] + e.cost) {
d[e.to] = d[u] + e.cost;
p[e.to] = G[u][i];
a[e.to] = min(a[u], e.cap - e.flow);
if(!inq[e.to]) {
inq[e.to]++;
que.push(e.to);
}
}
}
}
if(d[t] == INF) return false;
flow += a[t];
cost += d[t] * a[t];
int u = t;
while (u != s) {
edges[p[u]].flow += a[t];
edges[p[u]^1].flow -= a[t];
u = edges[p[u]].from;
}
return true;
}
int MinMaxflow(int s, int t) {
int flow = 0, cost = 0;
while (SPFA(s, t, flow, cost));
maxflow = flow; mincost = cost;
return cost;
}
};
int id[maxn][maxn];
int main()
{
int n, m, s, t, a, b;
scanf("%d%d%d%d", &a, &b, &n, &m);
MCMF solve;
int tot = 0;
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++)
id[i][j] = ++tot;
}
for (int i = 0; i <= n; i++) {
for (int j = 1; j <= m; j++) {
int x;
scanf("%d", &x);
solve.add(id[i][j - 1], id[i][j], 1, -x);
solve.add(id[i][j - 1], id[i][j], INF, 0);
}
}
for (int j = 0; j <= m; j++) {
for (int i = 1; i <= n; i++) {
int x;
scanf("%d", &x);
solve.add(id[i - 1][j], id[i][j], 1, -x);
solve.add(id[i - 1][j], id[i][j], INF, 0);
}
}
s = id[n][m] + 1, t = s + 1;
for (int i = 1; i <= a; i++) {
int k, x, y;
scanf("%d%d%d", &k, &x, &y);
solve.add(s, id[x][y], k, 0);
}
for (int i = 1; i <= b; i++) {
int k, x, y;
scanf("%d%d%d", &k, &x, &y);
solve.add(id[x][y], t, k, 0);
}
printf("%d\n", -solve.MinMaxflow(s, t));
}