5pts为什么
查看原帖
5pts为什么
895312
Archy_楼主2024/8/5 11:48

开了long long阿

#include <iostream>
#include <cstdio> 
#define int long long
using namespace std;

const int N = 1000005;
const int M = 2000005;
int n, ans;
int siz[N], head[N], cnt;

struct node {
	int to, next, w;
} e[M];

inline int rd(){
	int w = 1, x = 0;
    char c = getchar();
	while(c < 48 || c > 57) {
		if(c == 45) w *= -1;
		c = getchar();
	}
	while(c >= 48 && c<= 57) {
		x = (x << 1) + (x << 3) + (c ^ 48);
		c = getchar();
	}
	return x * w;
}

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

void dfs(int u, int fa) {
	siz[u] = 1;
	for(int i = head[u]; i; i = e[i].next) {
		int v = e[i].to;
		if(v == fa) continue;
		dfs(v, u);
		siz[u] += siz[v];
		ans += e[i].w * abs(2 * siz[v] - n);
	}
}

signed main() {
	int n = rd();
	for(int i = 1; i < n; i++) {
		int u = rd(), v = rd(), w = rd();
		add(u, v, w), add(v, u, w);
	}
	dfs(1, 1);
	cout << ans;
	return 0;
}
2024/8/5 11:48
加载中...