T444324 世界树
T444324 世界树
设一条边为
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define pb push_back
const int N = 3e5 + 10;
int n, ans, fa[N], tag[N], siz[N];
struct node
{
int a, b, c;
}a[N];
bool cmp(node x, node y)
{
return x.c > y.c;
}
void insert()
{
cin >> n;
for(int i = 1; i < n; i++) cin >> a[i].a >> a[i].b >> a[i].c;
}
int find(int x)
{
if(fa[x] == x) return x;
if(fa[fa[x]] == fa[x]) return fa[x];
int new_fa = find(fa[x]);
tag[x] += tag[fa[x]];
return fa[x] = new_fa;
}
void mer(int x, int y, int z)
{
x = find(x), y = find(y);
tag[x] += z * siz[y];
tag[y] += z * siz[x];
fa[y] = x;
siz[x] += siz[y];
tag[y] -= tag[x];
}
void work()
{
insert();
sort(a + 1, a + n, cmp);
for(int i = 1; i <= n; i++) fa[i] = i, siz[i] = 1;
for(int i = 1; i <= n; i++)
mer(a[i].a, a[i].b, a[i].c);
for(int i = 1; i <= n; i++)
{
int root = find(i);
if(fa[i] == i) cout << tag[i] << endl;
else cout << tag[i] + tag[root] << endl;
}
}
signed main()
{
ios::sync_with_stdio(0);
cout.tie(0);
cin.tie(0);
work();
return 0;
}