Dinic 50pts 求调
查看原帖
Dinic 50pts 求调
1112264
YZZCDS楼主2025/8/3 16:16
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

inline ll read() {
	ll f = 1, x = 0;
	char ch = getchar();
	while (ch < '0' || ch > '9') {
		if (ch == '-') f = -1;
		ch = getchar();
	}
	while (ch >= '0' && ch <= '9') {
		x = x * 10 + ch - '0';
		ch = getchar();
	}
	return x * f;
}

inline void write(ll x) {
	if (x < 0) x = -x, putchar('-');
	if (x > 9) write(x/10);
	putchar('0'+x%10);
}

inline void writeln(ll x) {
	write(x);
	putchar('\n');
}

struct edge {
	ll v, w, next;
} e[1000005];
ll head[100005], cnt = 1;

void add_edge(ll u, ll v, ll w) {
	e[++cnt] = {v, w, head[u]};
	head[u] = cnt;
}

ll n, root, a, b, c;

void dfs1(ll u, ll fa) {
	ll child = 0;
	for (int i = head[u]; i; i = e[i].next) {
		ll v = e[i].v, w = e[i].w;
		if (v == fa) {
			e[i].w = 0;
			continue;
		}
		dfs1(v, u);
		child ++;
	}
	if (!child) {
		add_edge(u, n+1, 1e9);
		add_edge(n+1, u, 0);
	}
}

ll now[100005], dep[100005];

bool bfs(ll s, ll t) {
	fill(dep, dep+100000, 1e9);
	now[s] = head[s];
	dep[s] = 0;
	queue<ll> q;
	q.push(s);
	while (!q.empty()) {
		ll u = q.front();
		q.pop();
		for (int i = now[u]; i; i = e[i].next) {
			ll v = e[i].v, w = e[i].w;
			if (w > 0 && dep[v] == 1e9) {
				dep[v] = dep[u] + 1;
				now[v] = head[v];
				q.push(v);
				if (v == t) return 1;
			}
		}
	}
	return 0;
}

ll dfs(ll s, ll t, ll u, ll sum) {
	if (u == t) return sum;
	ll k = 0, flow = 0;
	for (int i = now[u]; i && sum > 0; i = e[i].next) {
		now[u] = i;
		ll v = e[i].v, w = e[i].w;
		if (w > 0 && dep[v] == dep[u] + 1) {
			k = dfs(s, t, v, min(sum, w));
			if (!k) dep[v] = 1e9;
			e[i].w -= k;
			e[i^1].w += k;
			sum -= k;
			flow += k;
		}
	}
	return flow;
}

ll Dinic(ll s, ll t) {
	ll res = 0;
	while (bfs(s, t)) res += dfs(s, t, s, 1e9);
	return res;
}

ll ans;

int main() {
	n = read();
	root = read();
	for (int i = 1; i < n; i ++) {
		a = read(), b = read(), c = read();
		add_edge(a, b, c), add_edge(b, a, c);
	}
	dfs1(root, -1);
	ans = Dinic(root, n+1);
	write(ans);
	return 0;
}
2025/8/3 16:16
加载中...