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
| #include <cstdio> #include <vector> #include <utility> #include <algorithm>
using namespace std;
const auto U = [](auto x) { return [x](auto ...y) { return x(x, y...); }; }; vector<pair<int, int>> web[100005]; bool forbid[100005]; class fenwick { long long st[100005]; public: void vadd(int pos, int val, int n) { pos++; do { st[pos] += val; } while((pos += pos & -pos) <= n); } long long qsum(int pos) { pos++; long long sum = 0; do { sum += st[pos]; } while(pos -= pos & -pos); return sum; } } fw;
int main() { int n, l, r; scanf("%d%d%d", &n, &l, &r); for(int i=2;i<=n;i++) { int u, v, w; scanf("%d%d%d", &u, &v, &w); web[u].push_back({v, w}); web[v].push_back({u, w}); } auto cent = [](int rt) -> int { int tot = 0; U([&](auto &&self, int u, int fa) -> void { tot++; for(const auto &[v, w] : web[u]) if(v != fa && !forbid[v]) self(self, v, u); })(rt, 0); return -U([&](auto &&self, int u, int fa) -> int { int sum = 1, maxn = 0; for(const auto &[v, w] : web[u]) if(v != fa && !forbid[v]) { int res = self(self, v, u); if(res < 0) return res; sum += res; maxn = max(maxn, res); } maxn = max(maxn, tot - sum); if(maxn <= tot / 2) return -u; else return sum; })(rt, 0); }; auto calc = [l, r](int rt, int vlen, int vmax) -> long long { vector<pair<int, int>> vpii; U([&](auto &&self, int u, int fa, int len, int maxn) -> void { vpii.push_back({maxn, len}); for(const auto &[v, w] : web[u]) if(v != fa && !forbid[v]) self(self, v, u, len + 1, max(maxn, w)); })(rt, 0, vlen, vmax); sort(vpii.begin(), vpii.end()); long long sum = 0; for(const auto &[maxn, len] : vpii) { if(len <= r) sum += maxn * fw.qsum(r - len); if(len <= l - 1) sum -= maxn * fw.qsum(l - len - 1); fw.vadd(len, 1, 100000); } for(const auto &[maxn, len] : vpii) { fw.vadd(len, -1, 100000); } return sum; }; printf("%lld\n", U([&](auto &&self, int u) -> long long { u = cent(u); long long sum = calc(u, 0, 0); forbid[u] = true; for(const auto &[v, w] : web[u]) { if(!forbid[v]) sum -= calc(v, 1, w); } for(const auto &[v, w] : web[u]) { if(!forbid[v]) sum += self(self, v); } return sum; })(1) * 2); return 0; }
|