洛谷 P4012 深海机器人问题 题解

#include <bits/stdc++.h>
#define rep(i, a, b) for (int i = a; i <= b; i++)
#define per(i, a, b) for (int i = a; i >= b; i--)
#define pb push_back
#define pii pair<int, int>
#define ll long long
//#define inf 0x3f3f3f3f
using namespace std;
const int N = 20010, M = 500005, inf = 1 << 29;
int n, m, s ,t, tot;
long long maxflow = 0, ans = 0;
int ver[M], edge[M], cost[M], Next[M], Head[N];
int d[N], incf[N], pre[N], v[N];
void add(int x, int y, int z, int c) {
    //cout << x << " " << y << " "  << z << " " << c << '\n';
	// 正向边,初始容量z,单位费用c
	ver[++tot] = y, edge[tot] = z, cost[tot] = c;
	Next[tot] = Head[x], Head[x] = tot;
	// 反向边,初始容量0,单位费用-c,与正向边“成对存储”
	ver[++tot] = x, edge[tot] = 0, cost[tot] = -c;
	Next[tot] = Head[y], Head[y] = tot;
}
bool spfa() {
	queue<int> q;
	memset(d, 0x6f, sizeof(d)); // INF 计算最大费用流的时候0x3f改为0xcf,即-INF
	memset(v, 0, sizeof(v));
	q.push(s); d[s] = 0; v[s] = 1; pre[t] = -1; // SPFA 求最长路
	incf[s] = 1 << 30; // 增广路上各边的最小剩余容量
	while (q.size()) {
		int x = q.front(); 
        q.pop();
        v[x] = 0; 
		for (int i = Head[x]; i; i = Next[i]) {
			if (!edge[i]) continue; // 剩余容量为0,不在残量网络中,不遍历
			int y = ver[i];
			if (d[y] > d[x] + cost[i]) {//计算最大费用流的时候>改成<
				d[y] = d[x] + cost[i];
				incf[y] = min(incf[x], edge[i]);
				pre[y] = i; // 记录前驱,便于找到最长路的实际方案
				if (!v[y]) v[y] = 1, q.push(y);
			}
		}
	}
	return pre[t] != -1;// 汇点不可达,已求出最大流
	
}
//更新最长增广路及其反向边的剩余容量
void update() {
	int x = t;
	while (x != s) {
		int i = pre[x];
		edge[i] -= incf[t];
		edge[i ^ 1] += incf[t]; // 利用“成对存储”的xor 1技巧
		x = ver[i ^ 1];
	}
	maxflow += incf[t];
	ans += d[t] * incf[t];
}
inline int num(int i, int j) {
    return 18 * (i - 1) + j;
}
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    tot = 1;
    int a, b, p, q;
    cin >> a >> b;
    cin >> p >> q;
    s = 10005;
    t = 10006;
    for (int i = 1; i <= p + 1; i++) {
        for (int j = 1; j <= q; j++) {
            int v;
            cin >> v;
            add(num(i, j), num(i, j + 1), 1, -v);
            add(num(i, j), num(i, j + 1), inf, 0);
        }
    }
    for (int i = 1; i <= q + 1; i++) {
        for (int j = 1; j <= p; j++) {
            int v;
            cin >> v;
            add(num(j, i), num(j + 1, i), 1, -v);
            add(num(j, i), num(j + 1, i), inf, 0);
        }
    }
    for (int i = 1; i <= a; i++) {
        int k, x, y;
        cin >> k >> x >> y;
        add(s, num(x + 1, y + 1), k, 0);
    }
    for (int i = 1; i <= b; i++) {
        int r, x, y;
        cin >> r >> x >> y;
        add(num(x + 1, y + 1), t, r, 0);
    }
    while (spfa()) update();
    cout << -ans << '\n';
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值