# hdu 6162 Ch’s gift 树链剖分 + 离线查询

xiaoxiao2021-02-28  8

### 题目：

http://acm.hdu.edu.cn/showproblem.php?pid=6162

### 思路：

#include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 100000 + 10, INF = 0x3f3f3f3f; struct edge { int to, next; } g[N*2]; struct node { int l, r; ll sum; } s[N*4]; struct qnode { int s, t, val, id; }q[N*2], x[N]; int cnt, head[N]; int dep[N], siz[N], son[N], top[N], fat[N], id[N]; int d[N][2]; int num; ll ansl[N], ansr[N]; void init() { cnt = 0; memset(head, -1, sizeof head); num = 0; } void add_edge(int v, int u) { g[cnt].to = u, g[cnt].next = head[v], head[v] = cnt++; } void dfs1(int v, int fa, int d) { dep[v] = d, fat[v] = fa, siz[v] = 1, son[v] = 0; for(int i = head[v]; i != -1; i = g[i].next) { int u = g[i].to; if(u != fa) { dfs1(u, v, d + 1); siz[v] += siz[u]; if(siz[son[v]] < siz[u]) son[v] = u; } } } void dfs2(int v, int tp) { top[v] = tp, id[v] = ++num; if(son[v]) dfs2(son[v], tp); for(int i = head[v]; i != -1; i = g[i].next) { int u = g[i].to; if(u != son[v] && u != fat[v]) dfs2(u, u); } } void push_up(int k) { s[k].sum = s[k<<1].sum + s[k<<1|1].sum; } void build(int l, int r, int k) { s[k].l = l, s[k].r = r; if(l == r) { s[k].sum = 0; return; } int mid = (l + r) >> 1; build(l, mid, k << 1); build(mid + 1, r, k << 1|1); push_up(k); } void update(int v, int c, int k) { if(s[k].l == s[k].r) { s[k].sum = c; return; } int mid = (s[k].l + s[k].r) >> 1; if(v <= mid) update(v, c, k << 1); else update(v, c, k << 1|1); push_up(k); } ll query(int l, int r, int k) { if(l <= s[k].l && s[k].r <= r) return s[k].sum; int mid = (s[k].l + s[k].r) >> 1; ll ans = 0; if(l <= mid) ans += query(l, r, k << 1); if(r > mid) ans += query(l, r, k << 1|1); return ans; } ll Query(int v, int u) { int t1 = top[v], t2 = top[u]; ll ans = 0; while(t1 != t2) { if(dep[t1] < dep[t2]) swap(t1, t2), swap(v, u); ans += query(id[t1], id[v], 1); v = fat[t1]; t1 = top[v]; } if(dep[v] > dep[u]) swap(v, u); return ans + query(id[v], id[u], 1); } int main() { int n, m; while(~ scanf("%d%d", &n, &m)) { init(); for(int i = 1; i <= n; i++) scanf("%d", &x[i].val), x[i].id = i; sort(x + 1, x + 1 + n, [](qnode a, qnode b){return a.val < b.val;}); int a, b, c, d; for(int i = 1; i <= n-1; i++) { scanf("%d%d", &a, &b); add_edge(a, b); add_edge(b, a); } dfs1(1, 0, 1); dfs2(1, 1); build(1, num, 1); int k = 0; for(int i = 1; i <= m; i++) { scanf("%d%d%d%d", &a, &b, &c, &d); q[++k].s = a, q[k].t = b, q[k].val = c-1, q[k].id = i*2; q[++k].s = a, q[k].t = b, q[k].val = d, q[k].id = i*2+1; } sort(q + 1, q + 1 + k, [](qnode a, qnode b){return a.val < b.val;}); int en = 1; for(int i = 1; i <= k; i++) { while(en <= n && x[en].val <= q[i].val) update(id[x[en].id], x[en].val, 1), en++; if(q[i].id & 1) ansr[q[i].id/2] = Query(q[i].s, q[i].t); else ansl[q[i].id/2] = Query(q[i].s, q[i].t); } for(int i = 1; i <= m; i++) printf("%lld%c", ansr[i]-ansl[i], i == m ? '\n' : ' '); } return 0; }