提交时间:2026-02-09 21:02:48

运行 ID: 39969

#pragma GCC optimize("Ofast,no-stack-protector,inline,fast-math,unroll-loops,omit-frame-pointer") #define NDEBUG #include <algorithm> #include <cctype> #include <cstdio> #include <utility> #include <vector> using namespace std; using i64 = long long; struct IO { static constexpr unsigned MAX_LEN = 1 << 28; char buf[MAX_LEN], *p1, *p2; char pbuf[MAX_LEN], *pp; IO() : p1(buf) , p2(buf) , pp(pbuf) { } ~IO() { fwrite_unlocked(pbuf, 1, pp - pbuf, stdout); } char getch() { if (p1 == p2) p2 = (p1 = buf) + fread_unlocked(buf, 1, MAX_LEN, stdin); return p1 == p2 ? ' ' : *p1++; } IO& read(unsigned& x) { char ch = getch(); x = 0; for (; !isdigit(ch); ch = getch()) ; for (; isdigit(ch); ch = getch()) x = x * 10 + (ch - '0'); return *this; } void push(const char& c) { if (pp - pbuf == MAX_LEN) { fwrite_unlocked(pbuf, 1, MAX_LEN, stdout); pp = pbuf; } *pp++ = c; } IO& write(unsigned x) { if (x == 0) { push('0'); return *this; } unsigned top = 0, ch[40]; do { ch[top++] = x % 10; x /= 10; } while (x > 0); while (top > 0) push('0' + ch[--top]); return *this; } IO& write(unsigned x, char lst) { write(x); push(lst); return *this; } } io; vector<vector<pair<unsigned, unsigned>>> idx; vector<vector<unsigned>> tree; vector<unsigned> a; void prepare(unsigned u, unsigned fa = 0) { auto& id = idx[u]; for (auto v : tree[u]) { id.emplace_back(v, a[v]); if (v != fa) prepare(v, u); } } inline unsigned query(unsigned u, unsigned l, unsigned r) { const auto& id = idx[u]; return lower_bound(id.begin(), id.end(), make_pair(l, 0U))->second - lower_bound(id.begin(), id.end(), make_pair(r + 1, 0U))->second; } int main() { unsigned n, q; io.read(n); io.read(q); a.resize(n + 1); for (unsigned i = 1; i <= n; ++i) io.read(a[i]); tree.resize(n + 1); for (unsigned i = 1; i < n; ++i) { unsigned u, v; io.read(u); io.read(v); tree[u].push_back(v); tree[v].push_back(u); } for (unsigned i = 1; i <= n; ++i) sort(tree[i].begin(), tree[i].end()); idx.resize(n + 1); prepare(1); for (unsigned i = 1; i <= n; ++i) { idx[i].emplace_back(n + 1, 0); for (int j = idx[i].size() - 3; j >= 0; --j) idx[i][j].second += idx[i][j + 1].second; } while (q-- > 0) { unsigned u, l, r; io.read(u); io.read(l); io.read(r); io.write(query(u, l, r), '\n'); } return 0; }