如果嫌 CF 评测机太慢,有 双倍经验。
考虑做一个类似于欧拉序求 LCA 的过程。
先把欧拉序求出来,然后由于 $d(u,v)=dis(u)+dis(v)-2dis(lca)$,所以相当于要最大化 $dis(u),dis(v)$,最小化 $dis(lca)$。
这可以线段树维护 $Maxdis,Mindis,dis(u)-2dis(lca),-2dis(lca)+dis(v),dis(u)-2dis(lca)+dis(v)$。对于更改一条边的值相当于修改子树内的区间。
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 15, M = N << 1;
int n, q;
int h[N], e[M], ne[M], idx = 0;
long long w[M], ww[M], lim;
void add(int a, int b, long long c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
int dfn[N << 1], st[N], ed[N], tot = 0;
int pos[M];
long long dis[N];
void dfs(int u, int father) {
dfn[++tot] = u, st[u] = tot;
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (v == father) continue;
pos[(i >> 1) + 1] = v, dis[v] = dis[u] + w[i];
dfs(v, u);
dfn[++tot] = u;
}
ed[u] = tot;
}
struct Tree {
int l, r;
long long Min, Max;
long long lm, mr, mx;
long long flag;
} tr[N << 3];
void pushup(int u) {
tr[u].Min = min(tr[u << 1].Min, tr[u << 1 | 1].Min);
tr[u].Max = max(tr[u << 1].Max, tr[u << 1 | 1].Max);
tr[u].lm = max({tr[u << 1].lm, tr[u << 1 | 1].lm, tr[u << 1].Max - 2ll * tr[u << 1 | 1].Min});
tr[u].mr = max({tr[u << 1].mr, tr[u << 1 | 1].mr, tr[u << 1 | 1].Max - 2ll * tr[u << 1].Min});
tr[u].mx = max({tr[u << 1].mx, tr[u << 1 | 1].mx, tr[u << 1].lm + tr[u << 1 | 1].Max, tr[u << 1].Max + tr[u << 1 | 1].mr});
}
void update(int u, long long d) { //+d
tr[u].Min += d, tr[u].Max += d;
tr[u].lm -= d, tr[u].mr -= d; //左右端点可能是 lca
//tr[u].mx 不变
tr[u].flag += d;
}
void pushdown(int u) {
if (tr[u].flag) {
update(u << 1, tr[u].flag);
update(u << 1 | 1, tr[u].flag);
tr[u].flag = 0ll;
}
}
void build(int u, int l, int r) {
tr[u].l = l, tr[u].r = r;
if (l == r) {
long long val = dis[dfn[l]];
tr[u].Max = tr[u].Min = val;
tr[u].lm = tr[u].mr = -val;
tr[u].mx = 0;
return;
}
int mid = l + r >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
pushup(u);
}
void change(int u, int l, int r, long long d) {
if (l > r || tr[u].l > r || tr[u].r < l) return;
if (tr[u].l >= l && tr[u].r <= r) return update(u, d);
pushdown(u);
int mid = tr[u].l + tr[u].r >> 1;
if (l <= mid) change(u << 1, l, r, d);
if (r > mid) change(u << 1 | 1, l, r, d);
pushup(u);
}
long long query() { return tr[1].mx; }
int main() {
scanf("%d%d%lld", &n, &q, &lim);
for (int i = 1; i <= n; i++) h[i] = -1;
for (int i = 1; i < n; i++) {
int a, b; long long c; scanf("%d%d%lld", &a, &b, &c);
ww[i] = c;
add(a, b, c), add(b, a, c);
}
dfs(1, 0);
build(1, 1, tot);
long long lst = 0;
while (q--) {
long long d, e; scanf("%lld%lld", &d, &e);
long long D = (d + lst) % (n - 1) + 1, E = (e + lst) % lim;
long long Delta = E - ww[D];
change(1, st[pos[D]], ed[pos[D]], Delta);
lst = query();
ww[D] = E;
printf("%lld\n", lst);
}
return 0;
}