提交时间:2022-07-13 12:55:07
运行 ID: 51695
#include <bits/stdc++.h> using namespace std; const int MXN = 100005; const int MXQ = 1670005; int head[MXN], to[MXN << 1], nxt[MXN << 1], len[MXN << 1], egsz; int dep[MXN], siz[MXN], fa[MXN], hson[MXN], fae[MXN]; int itox[MXN], xtoi[MXN], anc[MXN], cid; int blcnt[MXN], cnt[MXN]; int ans[MXN], qv[MXN]; int N, M, VBW, SQT; void addedge(int f, int t, int w) { to[egsz] = t, len[egsz] = w, nxt[egsz] = head[f], head[f] = egsz++; to[egsz] = f, len[egsz] = w, nxt[egsz] = head[t], head[t] = egsz++; } void dfs1(int f, int x) { fa[x] = f; siz[x] = 1; hson[x] = -1; for (int i(head[x]); ~i; i = nxt[i]) { if (to[i] == f) continue; dep[to[i]] = dep[x] + 1; fae[to[i]] = len[i]; dfs1(x, to[i]); siz[x] += siz[to[i]]; if (!~hson[x] || siz[to[i]] > siz[hson[x]]) hson[x] = to[i]; } } void dfs2(int x, int a) { xtoi[x] = cid, itox[cid++] = x; anc[x] = a; if (!~hson[x]) return; dfs2(hson[x], a); for (int i(head[x]); ~i; i = nxt[i]) { if (to[i] == fa[x] || to[i] == hson[x]) continue; dfs2(to[i], to[i]); } } struct Question { int l, r, v, id; } qs[MXQ]; int qid; bool operator<(const Question& lhs, const Question& rhs) { if (lhs.l / SQT != rhs.l / SQT) return lhs.l / SQT < rhs.l / SQT; if ((lhs.l / SQT) & 1) return lhs.r > rhs.r; return lhs.r < rhs.r; } void chg(int v) { if (cnt[v]) --blcnt[v / VBW]; else ++blcnt[v / VBW]; cnt[v] ^= 1; } int main() { freopen("game.in", "r", stdin); freopen("game.out", "w", stdout); cin >> N; fill(head, head + N, -1); for (int i(1), u(0), v(0), w(0); i != N; ++i) cin >> u >> v >> w, --u, --v, addedge(u, v, w); dfs1(-1, 0); dfs2(0, 0); cin >> M; for (int i(0), u(0), v(0), r(0); i != M; ++i) { cin >> u >> v >> r; qv[i] = r; --u, --v; while (anc[u] != anc[v]) { if (dep[u] < dep[v]) swap(u, v); qs[qid].l = xtoi[anc[u]], qs[qid].r = xtoi[u] + 1; qs[qid].v = r, qs[qid].id = i; ++qid; u = fa[anc[u]]; } if (dep[u] < dep[v]) swap(u, v); qs[qid].l = xtoi[v] + 1, qs[qid].r = xtoi[u] + 1; qs[qid].v = r, qs[qid].id = i; ++qid; } VBW = N / max(sqrt(M * log2(N)), 1.0); SQT = sqrt(N); sort(qs, qs + qid); for (int i(0), L(0), R(0); i != qid; ++i) { while (L > qs[i].l) chg(fae[itox[--L]]); while (R < qs[i].r) chg(fae[itox[R++]]); while (L < qs[i].l) chg(fae[itox[L++]]); while (R > qs[i].r) chg(fae[itox[--R]]); int c(qs[i].v); for (; !cnt[c] && (c + 1) % VBW; --c); if (cnt[c]) { ans[qs[i].id] = max(ans[qs[i].id], c); continue; } for (c /= VBW; !blcnt[c]; --c); for (c = c * VBW + VBW - 1; !cnt[c] && c; --c); ans[qs[i].id] = max(ans[qs[i].id], c); } for (int i(0); i != M; ++i) { cout << qv[i] - ans[i] << endl; } return 0; }