AcWing 1255. 医院设置(树的重心)
原题链接
简单
作者:
白墙
,
2021-07-30 19:06:32
,
所有人可见
,
阅读 338
注意这里的size[u]定义是结点的权值
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1e5 + 10;
const int INF = 0x3f3f3f3f;
int ans = INF, po;
int h[N], ne[N], e[N], idx;
int w[N];
int n, sum;
bool st[N];
int dist[N];
int s[N];
void add (int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
void dfs (int x) {
s[x] = w[x];
st[x] = true;
int max_part = 0;
for (int i = h[x]; i != -1; i = ne[i] ) {
int y = e[i];
if (st[y]) continue;
dfs (y);
s[x] += s[y];
max_part = max (max_part, s[y]);
}
max_part = max (max_part, sum - s[x]);
if (max_part < ans) {
ans = max_part;
po = x;
}
}
void dfs2 (int x) {
st[x] = true;
for (int i = h[x]; i != -1; i = ne[i]) {
int y = e[i];
if (st[y]) continue;
dist[y] = dist[x] + 1;
dfs2 (y);
}
}
int main () {
cin >> n;
memset (h, -1, sizeof h);
for (int i = 1; i <= n;i ++) {
int a, b, c;
cin >> w[i] >> b >> c;
if (b) {
add (i, b), add (b, i);
}
if (c) {
add (i, c); add (c, i);
}
sum += w[i];
}
int root = 1;
dfs (root);
memset (st, false, sizeof st);
dfs2 (po);
int ans = 0;
for (int i = 1; i <= n; i ++)
ans += dist[i] * w[i];
cout << ans << endl;
return 0;
}