1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
| #include <bits/stdc++.h> #define pii pair<int, int>
using namespace std; const int N = 2e5 + 10; int n, m, k; int h[N], e[N << 1], ne[N << 1], w[N << 1], idx; bool vis[N], st[N]; pii d[N]; int tr[N], cnt; int tmp[N]; int res;
inline int read() { int x = 0, y = 1; char c = getchar(); while (c < '0' || c > '9') {if (c == '-') y = -1; c = getchar();} while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar(); return x * y; }
inline void add(int a, int b, int c) { e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++; }
inline int get_size(int u, int p) { if (vis[u]) return 0; int res = 1; for (int i = h[u]; ~i; i = ne[i]) { int v = e[i]; if (v == p) continue; res += get_size(v, u); } return res; }
inline int get_root(int u, int p, int all, int &root) { if (vis[u]) return 0; int sum = 1, now = 0; for (int i = h[u]; ~i; i = ne[i]) { int v = e[i]; if (v == p) continue; int k = get_root(v, u, all, root); now = max(now, k), sum += k; } now = max(now, all - sum); if (now <= all / 2) root = u; return sum; }
inline void get_dist(int u, int p, int dist, int black) { if (vis[u]) return; d[++cnt] = {dist, black}; for (int i = h[u]; ~i; i = ne[i]) { int v = e[i]; if (v == p) continue; get_dist(v, u, dist + w[i], black + st[v]); } }
inline void add(int x, int v) { for (; x <= k + 1; x += x & -x) tr[x] = max(tr[x], v); }
inline void del(int x) { for (; x <= k + 1; x += x & -x) tr[x] = 0; }
inline int ask(int x) { int res = 0; for (; x; x -= x & -x) res = max(res, tr[x]); return res; }
inline void calc(int u) { int now = 0; for (int i = h[u]; ~i; i = ne[i]) { int v = e[i]; if (vis[v]) continue; cnt = 0, get_dist(v, u, w[i], st[v]); for (int j = 1; j <= cnt; j++) if (d[j].second + st[u] <= k) res = max(res, d[j].first + ask(k - d[j].second - st[u] + 1)); for (int j = 1; j <= cnt; j++) tmp[++now] = d[j].second, add(d[j].second + 1, d[j].first); } for (int i = 1; i <= now; i++) del(tmp[i] + 1); }
inline void dfs(int u) { if (vis[u]) return; get_root(u, -1, get_size(u, -1), u); vis[u] = true; calc(u); for (int i = h[u]; ~i; i = ne[i]) dfs(e[i]); }
int main() { memset(h, -1, sizeof h); n = read(), k = read(), m = read(); for (int i = 1; i <= m; i++) { int x = read(); st[x] = 1; } for (int i = 1; i <= n - 1; i++) { int a = read(), b = read(), c = read(); add(a, b, c), add(b, a, c); } dfs(1); printf("%d\n", res); return 0; }
|