# CodeForces 1110F Nearest Leaf | 线段树/换根

## 题目描述

$n, m \le 500000$

## 代码

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <cassert>
#include <vector>
#define space putchar(' ')
#define enter putchar('\n')
using namespace std;
typedef long long ll;
template <class T>
char c;
bool op = 0;
while(c = getchar(), c < '0' || c > '9')
if(c == '-') op = 1;
x = c - '0';
while(c = getchar(), c >= '0' && c <= '9')
x = x * 10 + c - '0';
if(op) x = -x;
}
template <class T>
void write(T x){
if(x < 0) putchar('-'), x = -x;
if(x >= 10) write(x / 10);
putchar('0' + x % 10);
}

const int N = 500005;
const ll INF = 0x3f3f3f3f3f3f3f3f;
int n, m;
int ncnt, dfn[N], idx[N], ed[N];
int lcnt, llst[N], lnum[N], prel[N], nxtl[N];
ll w[N], dis[N], data[4*N], lazy[4*N], ans[N];
vector <int> son[N];

struct Query {
int id, u, l, r;
bool operator < (const Query &b) const {
return dfn[u] < dfn[b.u];
}
} qry[N];
int qpos = 1;

void dfs1(int u, int pre){
dfn[u] = ++ncnt;
idx[ncnt] = u;
for(auto v : son[u]){
dis[v] = dis[u] + w[v];
dfs1(v, u);
}
if(u != 1 && ncnt == dfn[u]){
lnum[u] = ++lcnt;
llst[lcnt] = u;
}
ed[u] = ncnt;
}

void modify(int k, ll x){
data[k] += x, lazy[k] += x;
}
void pushdown(int k){
if(!lazy[k]) return;
modify(k << 1, lazy[k]);
modify(k << 1 | 1, lazy[k]);
lazy[k] = 0;
}
void change(int k, int l, int r, int ql, int qr, ll x){
if(ql <= l && qr >= r) return void(modify(k, x));
pushdown(k);
int mid = (l + r) >> 1;
if(ql <= mid) change(k << 1, l, mid, ql, qr, x);
if(qr > mid) change(k << 1 | 1, mid + 1, r, ql, qr, x);
data[k] = min(data[k << 1], data[k << 1 | 1]);
}
ll query(int k, int l, int r, int ql, int qr){
if(ql <= l && qr >= r) return data[k];
pushdown(k);
int mid = (l + r) >> 1;
ll ret = INF;
if(ql <= mid) ret = query(k << 1, l, mid, ql, qr);
if(qr > mid) ret = min(ret, query(k << 1 | 1, mid + 1, r, ql, qr));
return ret;
}
void build_tree(int k, int l, int r){
if(l == r) return void(data[k] = dis[llst[l]]);
int mid = (l + r) >> 1;
build_tree(k << 1, l, mid);
build_tree(k << 1 | 1, mid + 1, r);
data[k] = min(data[k << 1], data[k << 1 | 1]);
}

void dfs2(int u, int pre){
while(qry[qpos].u == u){
ans[qry[qpos].id] = query(1, 1, lcnt, qry[qpos].l, qry[qpos].r);
qpos++;
}
for(auto v : son[u]){
change(1, 1, lcnt, 1, lcnt, w[v]);
change(1, 1, lcnt, nxtl[dfn[v]], prel[ed[v]], -2 * w[v]);
dfs2(v, u);
change(1, 1, lcnt, 1, lcnt, -w[v]);
change(1, 1, lcnt, nxtl[dfn[v]], prel[ed[v]], 2 * w[v]);
}
}

int main(){

for(int i = 2, u; i <= n; i++){
son[u].push_back(i);
}
dfs1(1, 0);
for(int i = 1, t = 1; i <= n; i++){
if(lnum[idx[i]]) t = lnum[idx[i]];
prel[i] = t;
}
for(int i = n, t = lcnt; i; i--){
if(lnum[idx[i]]) t = lnum[idx[i]];
nxtl[i] = t;
}
for(int i = 1; i <= m; i++){