【BZOJ2055】80人环游世界【有上下界的最小费用最大流】

【题目链接】

随便建...

/* Think Thank Thunk */
#include 
#include 
#include 

using namespace std;

const int maxn = 205, maxm = 250005, maxq = 100005, inf = 0x3f3f3f3f;

int n, m, head[maxn], cnt, bg, ed, du[maxn], depth[maxn], way[maxn], q[maxq];
bool vis[maxn];

struct _edge {
	int v, w, c, next;
} g[maxm << 1];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline void add(int u, int v, int w, int c) {
	g[cnt] = (_edge){v, w, c, head[u]};
	head[u] = cnt++;
}

inline void insert(int u, int v, int w, int c) {
	add(u, v, w, c); add(v, u, 0, -c);
}

inline bool spfa() {
	for(int i = 0; i <= ed; i++) depth[i] = inf;
	int h = 0, t = 0, u, i; depth[q[t++] = bg] = 0;
	while(h != t) for(i = head[u = q[h++]], vis[u] = 0; ~i; i = g[i].next) if(g[i].w && depth[g[i].v] > depth[u] + g[i].c) {
		depth[g[i].v] = depth[u] + g[i].c;
		way[g[i].v] = i;
		if(!vis[g[i].v]) vis[q[t++] = g[i].v] = 1;
	}
	return depth[ed] != inf;
}

inline int back() {
	int flow = inf, res = 0;
	for(int u = ed; u != bg; u = g[way[u] ^ 1].v) flow = min(flow, g[way[u]].w);
	for(int u = ed; u != bg; u = g[way[u] ^ 1].v) g[way[u]].w -= flow, g[way[u] ^ 1].w += flow, res += flow * g[way[u]].c;
	return res;
}

int main() {
	n = iread(); m = iread(); bg = 0; ed = (n << 1) + 2;
	for(int i = 0; i <= ed; i++) head[i] = -1; cnt = 0;

	insert(bg, ed - 1, m, 0);
	for(int i = 1; i <= n; i++) {
		int w = iread();
		insert(i, i + n, 0, 0);
		du[i] -= w; du[i + n] += w;
		insert(ed - 1, i, inf, 0);
	}
	for(int i = 1; i <= n; i++) for(int j = i + 1; j <= n; j++) {
		int w = iread();
		if(~w) insert(i + n, j, inf, w);
	}
	for(int i = n << 1; i; i--)
		if(du[i] > 0) insert(bg, i, du[i], 0);
		else insert(i, ed, -du[i], 0);

	int ans = 0;
	while(spfa()) ans += back();
	printf("%d\n", ans);
	return 0;
}


你可能感兴趣的:(网络流)