AC(这道题要先好好读题嗷)

 •  12天前


#include <bits/stdc++.h>
using namespace std;
vector<vector<pair<int, int>>> adj;
long long sum = 0;
int n;

int dfs(int u, int parent) {
	int size = 1;

	for (auto &edge : adj[u]) {
		int v = edge.first;
		int c = edge.second;

		if (v == parent)
			continue;

		int csum = dfs(v, u);
		size += csum;
		sum += (long long)c * abs(n - 2 * csum);
	}

	return size;
}

int main() {

	cin >> n;
	if (n == 1) {
		cout << 0 << endl;
		return 0;
	}

	adj.resize(n + 1);


	for (int i = 0; i < n - 1; i++) {
		int a, b, c;
		cin >> a >> b >> c;
		adj[a].push_back({b, c});
		adj[b].push_back({a, c});
	}

	dfs(1, -1);

	cout << sum << endl;

	return 0;
}


评论:

thank you


み柒壹ン  •  12天前

请先登录,才能进行评论