CodeForces - 708D Incorrect Flow

Description

一张 \(n\) 个点 \(m\) 条边的有向图,每条边有一个流量上限 \(c\) 和当前流量 \(f\) 。你可以对 \(c\)\(f\) 修改,修改的代价为修改后与修改前的差的和。问使得每条边的 \(0 < f \le c\) 且除了 \(1\)\(n\) 以外每个点流量平衡的最小代价。

\(n,m\le 100,0\le c,f\le 10^6\)

Solution

费用流好题。

对于原图中的一条边 \((u,v,c,f)\)

  • \(d[u]-=f,d[v]+=f\)

  • \(f > c\)

    • \((v, u, f - c,0)\)
    • \((v,u,c,1)\)
    • \((u,v,\inf,2)\)
    • \(ans +=f-c\)
  • \(f\le c\)

    • \((v,u,f,1)\)
    • \((u,v,c-f,1)\)
    • \((u,v,inf,2)\)

由于 \(n\)\(1\) 流量不平衡,所以还要加 \((n,1,\inf,0)\)

对于每个点 \(i\) ,若 \(d[i] > 0\)\((S,i,d[i],0)\) ,反之 \((i,T,-d[i],0)\)

最后答案即为 \(ans+cost\)

#include<bits/stdc++.h>
using namespace std;

template <class T> void read(T &x) {
	x = 0; bool flag = 0; char ch = getchar(); for (; ch < '0' || ch > '9'; ch = getchar()) flag |= ch == '-';
	for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - 48; flag ? x = ~x + 1 : 0;
}

#define N 110
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define INF 0x3f3f3f3f

int S, T, flow, cost, head[N], tot = 1, dis[N], pre[N];
struct { int v, c, w, next; }e[100001];
queue<int> q;
bool inq[N];
inline void insert(int u, int v, int c, int w) {
	e[++tot].v = v, e[tot].c = c, e[tot].w = w, e[tot].next = head[u], head[u] = tot;
}
inline void add(int u, int v, int c, int w) {
	insert(u, v, c, w), insert(v, u, 0, -w);
}
bool spfa() {
	memset(dis, 0x3f, sizeof dis); dis[S] = 0, q.push(S);
	while (!q.empty()) {
		int u = q.front(); q.pop(), inq[u] = 0;
		for (int i = head[u], v; i; i = e[i].next) e[i].c && dis[v = e[i].v] > dis[u] + e[i].w ?
			dis[v] = dis[u] + e[i].w, pre[v] = i, (!inq[v] ? q.push(v), inq[v] = 1 : 0) : 0;
	}
	return dis[T] < INF;
}
void mcf() {
	int d = INF;
	for (int i = T; i != S; i = e[pre[i] ^ 1].v) d = min(d, e[pre[i]].c);
	for (int i = T; i != S; i = e[pre[i] ^ 1].v) e[pre[i]].c -= d, e[pre[i] ^ 1].c += d, cost += d * e[pre[i]].w;
	flow += d;
}

int d[N];

int main() {
	int n, m; read(n), read(m);
	T = n + 1;
	int ans = 0;
	rep(i, 1, m) {
		int u, v, c, f; read(u), read(v), read(c), read(f);
		d[u] -= f, d[v] += f;
		add(u, v, INF, 2);
		if (f >= c) ans += f - c, add(v, u, f - c, 0), add(v, u, c, 1);
		else add(v, u, f, 1), add(u, v, c - f, 1);
	}
	rep(i, 1, n) d[i] > 0 ? add(S, i, d[i], 0) : add(i, T, -d[i], 0);
	add(n, 1, INF, 0);
	while (spfa()) mcf();
	cout << ans + cost;
	return 0;
}
posted @ 2018-09-05 16:21  aziint  阅读(220)  评论(0编辑  收藏  举报
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.