You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
const int N = 500010, M = N << 1;
#define int long long
// 链式前向星
int e[M], h[N], idx, w[M], ne[M];
void add(int a, int b, int c = 0) {
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
int n, m, k;
int sz[N]; // 以u为根节点是否有人
int g[N]; // 从u出发把u子树上的人都送回家再回到u所需要的时间
int mx1[N]; // u的子树中最长链的长度
int mx2[N]; // u的子树中次长链
int up[N]; // 不在u的子树内距离u最远的那个人的家到u的距离
int id[N]; // 最长链条是哪条链
int ans[N]; // 从u出发把所有点都送回家再回到u的结果
// ans[i] -max(up[i],mx1[i]);
void dfs1(int u, int fa) {
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (v == fa) continue;
dfs1(v, u);
if (sz[v] == 0) continue;
g[u] += g[v] + 2 * w[i];
int now = mx1[v] + w[i];
if (now >= mx1[u]) {
mx2[u] = mx1[u];
mx1[u] = now;
id[u] = v;
} else if (now >= mx2[u])
mx2[u] = now;
sz[u] += sz[v];
}
}
void dfs2(int u, int fa) {
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (v == fa) continue;
if (sz[v] == k) {
ans[v] = g[v];
up[v] = 0;
} else if (sz[v] == 0) {
ans[v] = ans[u] + 2 * w[i];
up[v] = max(up[u], mx1[u]) + w[i];
} else if (sz[v] && sz[v] != k) {
ans[v] = ans[u];
if (id[u] == v)
up[v] = max(mx2[u], up[u]) + w[i];
else
up[v] = max(up[u], mx1[u]) + w[i];
}
dfs2(v, u);
}
}
signed main() {
// 初始化链式前向星
memset(h, -1, sizeof h);
cin >> n >> k; // n个节点,要接k个人
for (int i = 1; i < n; i++) { // n-1条边
int a, b, c;
cin >> a >> b >> c;
add(a, b, c), add(b, a, c);
}
for (int i = 1; i <= k; i++) {
int x;
cin >> x;
sz[x] = 1; // x节点有一个人
}
// 第一次dfs
dfs1(1, 0);
ans[1] = g[1];
// 第二次dfs
dfs2(1, 0);
for (int u = 1; u <= n; u++) cout << ans[u] - max(up[u], mx1[u]) << endl;
}