bzoj 2521 [Shoi2010]最小生成树 最小割建图

题面

题目传送门

解法

和bzoj 2561类似

问题转化为,每一次可以使某一条边的权值+1,问最少多少次以后这条边一定在最小生成树上

最小割即可

代码

#include <bits/stdc++.h>
#define N 1010
using namespace std;
template <typename node> void read(node &x) {
	x = 0; int f = 1; char c = getchar();
	while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
	while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); x *= f;
}
struct Node {
	int x, y, v;
} a[N];
struct Edge {
	int next, num, c;
} e[N * 10];
int n, m, k, s, t, cnt, cur[N], l[N];
void add(int x, int y, int c) {
	e[++cnt] = (Edge) {e[x].next, y, c};
	e[x].next = cnt;
}
void Add(int x, int y, int c) {
	add(x, y, c), add(y, x, 0);
	add(y, x, c), add(x, y, 0);
}
bool bfs(int s) {
	for (int i = 1; i <= n; i++) l[i] = -1;
	queue <int> q; q.push(s); l[s] = 0;
	while (!q.empty()) {
		int x = q.front(); q.pop();
		for (int p = e[x].next; p; p = e[p].next) {
			int k = e[p].num, c = e[p].c;
			if (c && l[k] == -1)
				l[k] = l[x] + 1, q.push(k);
		}
	}
	return l[t] != -1;
}
int dfs(int x, int lim) {
	if (x == t) return lim;
	int used = 0;
	for (int p = cur[x]; p; p = e[p].next) {
		int k = e[p].num, c = e[p].c;
		if (l[k] == l[x] + 1 && c) {
			int w = dfs(k, min(c, lim - used));
			e[p].c -= w, e[p ^ 1].c += w;
			if (e[p].c) cur[x] = p; used += w;
			if (used == lim) return lim;
		}
	}
	if (!used) l[x] = -1;
	return used;
}
int dinic() {
	int ret = 0;
	while (bfs(s)) {
		for (int i = 1; i <= n; i++)
			cur[i] = e[i].next;
		ret += dfs(s, INT_MAX);
	}
	return ret;
}
int main() {
	read(n), read(m), read(k);
	for (int i = 1; i <= m; i++)
		read(a[i].x), read(a[i].y), read(a[i].v);
	s = a[k].x, t = a[k].y, cnt = n;
	if (cnt % 2 == 0) cnt++;
	for (int i = 1; i <= m; i++)
		if (i != k && a[i].v <= a[k].v)
			Add(a[i].x, a[i].y, a[k].v - a[i].v + 1);
	cout << dinic() << "\n";
	return 0;
}

posted @ 2018-08-14 23:20  谜のNOIP  阅读(102)  评论(0编辑  收藏  举报