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
   | #include<bits/stdc++.h>
  using namespace std;
  constexpr int MAXN = 4e4 + 4;
  template<typename T> inline void read(T &x) {     int f = 1; x = 0;     char ch = getchar();     while (!isdigit(ch)) f = (ch == '-') ? -1 : 1, ch = getchar();     while (isdigit(ch)) x = x * 10 + ch - 48, ch = getchar();     x *= f; }
  vector< pair<int, int> > G[MAXN]; vector<int> vec;
  int n, k, tot, root, res; int sz[MAXN], dp[MAXN], dis[MAXN], vis[MAXN];
  inline void getRoot(int cur, int fa) {      sz[cur] = 1, dp[cur] = 0;     for (auto &e : G[cur]) {         int to = e.first, w = e.second;         if (to == fa || vis[to]) continue;         getRoot(to, cur);         sz[cur] += sz[to];         dp[cur] = max(dp[cur], sz[to]);      }     dp[cur] = max(dp[cur], tot - sz[cur]);     if (dp[cur] < dp[root]) root = cur; }
  inline void getDis(int cur, int fa) {      vec.emplace_back(dis[cur]);     for (auto &e : G[cur]) {         int to = e.first, w = e.second;         if (to == fa || vis[to]) continue;         dis[to] = dis[cur] + w;         getDis(to, cur);     } }
  inline void calc(int cur, int w, int type) {      dis[cur] = w, vec.clear(), getDis(cur, 0);     sort(vec.begin(), vec.end());     int l = 0, r = (int)vec.size() - 1;     while (l <= r) {         if (vec[l] + vec[r] <= k) res += type * (r - l), ++l;         else --r;     } }
  inline void dfs(int cur) {     vis[cur] = true, calc(root, 0, 1);     for (auto &e : G[cur]) {         int to = e.first, w = e.second;         if (vis[to]) continue;         calc(to, w, -1);          root = cur, tot = dp[root] = sz[to];          getRoot(to, root), dfs(root);     } }
  int main() {     read(n);     for (int i = 1, u, v, w; i < n; i++) {         read(u), read(v), read(w);         G[u].emplace_back(make_pair(v, w)), G[v].emplace_back(make_pair(u, w));     }     read(k);     root = 0, tot = dp[root] = n;     getRoot(1, root), dfs(root);     cout << res << endl;     return 0; }
   |