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
| #include <cstdio> #include <algorithm> #include <vector> using namespace std; template <class Type> void read(Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0'; if (flag) x = ~x + 1; } template <class Type, class ...rest> void read(Type &x, rest &...y) { read(x), read(y...); } template <class Type> void write(Type x) { if (x < 0) putchar('-'), x = ~x + 1; if (x > 9) write(x / 10); putchar(x % 10 + '0'); } void chkmin (int &x, int k) { if (k < x) x = k; } void chkmax (int &x, int k) { if (k > x) x = k; } typedef long long LL; typedef pair <int, int> PII; const int N = 1e5 + 10, M = 2e5 + 10; bool vis[N]; int n, m, g; LL tr[N]; int idx, hd[N], nxt[M], edg[M], wt[M]; void modify (int x, int k) { for (++x; x <= g; x += x & -x) tr[x] += k; } LL query (int x) { int res = 0; for (++x; x > 0; x -= x & -x) res += tr[x]; return res; } int Size (int x, int fa) { if (vis[x]) return 0; int res = 1; for (int i = hd[x]; i; i = nxt[i]) if (edg[i] ^ fa) res += Size(edg[i], x); return res; } int WeightCentre (int x, int fa, int tot, int &wc) { if (vis[x]) return 0; int sum = 1, mx = 0; for (int i = hd[x]; i; i = nxt[i]) if (edg[i] ^ fa) { int t = WeightCentre(edg[i], x, tot, wc); chkmax(mx, t), sum += t; } chkmax(mx, tot - sum); if (mx <= tot / 2) wc = x; return sum; } void Dist (int x, int fa, int s, int t, vector<PII> &q) { if (vis[x]) return; q.push_back(make_pair(s, t)); for (int i = hd[x]; i; i = nxt[i]) if (edg[i] ^ fa) Dist(edg[i], x, s + wt[i], t + 1, q); } LL get (vector<PII> p) { sort(p.begin(), p.end()); LL res = 0; int i = p.size(), j = 0; while (~--i) { while (j < i && p[j].first + p[i].first <= m) modify(p[j++].second, 1); if (j > i) modify(p[--j].second, -1); res += query(g - p[i].second); } return res; } LL calc (int x) { if (vis[x]) return 0; WeightCentre(x, -1, Size(x, -1), x); vis[x] = true; LL res = 0; vector <PII> p; p.push_back(make_pair(0, 0)); for (int i = hd[x]; i; i = nxt[i]) { vector <PII> q; Dist(edg[i], -1, wt[i], 1, q); res -= get(q); for (PII k : q) p.push_back(k); } res += get(p); for (int i = hd[x]; i; i = nxt[i]) res += calc(edg[i]); return res; } void add (int a, int b, int c) { nxt[++idx] = hd[a]; hd[a] = idx; edg[idx] = b; wt[idx] = c; } int main() { read(n, g, m); for (int i = 1, p, w; i < n; i++) read(p, w), add(i + 1, p, w), add(p, i + 1, w); write(calc(1)); return 0; }
|