1

噢莫加纳加加加  •  12天前


#include <iostream>
#include <cstring>
using namespace std;
#define N 10000005

int head[N], sum[N] = {0}, n, cnt = 0, ans = 0;

struct node {
	int to, w, next;
} e[N * 2];

void addEdge(int u, int v, int w) {
	e[cnt].to = v;
	e[cnt].w = w;
	e[cnt].next = head[u];
	head[u] = cnt;
	cnt++;
}

void dfs(int fa, int me) {
	sum[me] = 1;
	for (int i = head[me]; i >= 0; i = e[i].next) {
		int w = e[i].w;
		int son = e[i].to;
		if (son != fa) {
			dfs(me, son);
			ans += abs(sum[son] - (n - sum[son])) * w;
			sum[me] += sum[son];
		}
	}
}

int main() {
	cin >> n;
	memset(head, -1, sizeof head);
	for (int i = 1, u, v, w; i < n; i++) {
		cin >> u >> v >> w;
		addEdge(u, v, w);
		addEdge(v, u, w);
	}
	dfs(0, 1);
	cout << ans;
	return 0;
}

评论:

请先登录,才能进行评论