题面
来源:USACO 官网。模型收到的是同一份题面的文字。
Farmer Nhoj has trapped Bessie on a rooted tree with $N$ ($2 \le N \le 2 \cdot 10^5$) nodes, where node $1$ is the root. Scared and alone, Bessie makes the following move each second:
- If Bessie's current node has no children, then she will move to a random ancestor of the current node (excluding the node itself).
- Otherwise, Bessie will move to a random child of the current node.
Initially, Bessie is at node $x$, and her only way out is the exit located at node $y$ ($1\le x,y\le N$). For $Q$ ($1 \le Q \le 2 \cdot 10^5$) independent queries of $x$ and $y$, compute the expected number of seconds it would take Bessie to reach node $y$ for the first time if she started at node $x$, modulo $10^9+7$.
INPUT FORMAT (input arrives from the terminal / stdin):
The first line contains $N$ and $Q$.The next line contains $N-1$ integers $p_2, \ldots p_N$ describing the tree ($1\le p_i<i$). For each $2 \le i \le N$, there is an edge between nodes $i$ and $p_i$.
Each of the next $Q$ lines contains integers $x$ and $y$ representing the nodes for that query.
OUTPUT FORMAT (print output to the terminal / stdout):
For each query, output the expected number of seconds for Bessie to reach node $y$ for the first time starting at node $x$, modulo $10^9+7$.SAMPLE INPUT:
5 5 1 2 2 1 1 1 2 1 3 1 4 1 5 1
SAMPLE OUTPUT:
0 4 3 3 1In the $1$st query, the expected time to reach node $1$ from itself is $0$.
In the $3$rd query, after $1$ second, Bessie will be at node $1$ with probability $\frac{1}{2}$ and at node $2$ with probability $\frac{1}{2}$. Since the expected time to reach node $1$ from node $2$ is $4$, the expected time for Bessie to reach node $1$ starting at node $3$ is $1 + \frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 4 = 3$.
SAMPLE INPUT:
5 5 1 2 2 1 1 1 1 2 1 3 1 4 1 5
SAMPLE OUTPUT:
0 3 500000011 500000011 6In the $3$rd query, the expected time to reach node $3$ from node $1$ is $\frac{15}{2}$.
SAMPLE INPUT:
13 10 1 2 2 4 3 1 5 6 4 7 8 10 1 12 10 6 5 12 1 13 13 10 6 4 7 12 3 1 12 8 2 1
SAMPLE OUTPUT:
166666700 21 2 166666701 500000023 18 166666704 750000018 800000021 500000018
SCORING:
- Inputs 4-8: For all queries, $y=1$.
- Inputs 9-13: For all queries, $x=1$.
- Inputs 14-18: For each $2 \le i \le N$, $p_i$ is uniformly randomly chosen from the range $[1, i-1]$.
- Inputs 19-23: No additional constraints.
Problem credits: Avnith Vijayram
结果
Kimi K3.1 ProKimi
3/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 100采样 3 · 解出
- 29.8k平均输出 token(含思考) ↓
- 26.4输出速度 tokens/s ↑
- 1090 秒延迟 ↓
- 0.49×CPU 时间 / 官方解 ↓
- 同阶 3时间复杂度(相对官方解)
Kimi K3.1 Pro(high)Kimi high
2/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 13.0采样 3 · 答案错误
- 29.9k平均输出 token(含思考) ↓
- 26.4输出速度 tokens/s ↑
- 1090 秒延迟 ↓
- 0.55×CPU 时间 / 官方解 ↓
- 同阶 2时间复杂度(相对官方解)
DeepSeek Flash V4.1-1017DeepSeek
3/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 100采样 3 · 解出
- 48.2k平均输出 token(含思考) ↓
- 170.3输出速度 tokens/s ↑
- 288 秒延迟 ↓
- 0.43×CPU 时间 / 官方解 ↓
- 不可测 1、同阶 2时间复杂度(相对官方解)
MiniMax M3.1 FlashMiniMax
1/3
解出的采样 ↑
- 100采样 1 · 解出
- 30.4采样 2 · 答案错误
- 30.4采样 3 · 答案错误
- 99.7k平均输出 token(含思考) ↓
- 162.3输出速度 tokens/s ↑
- 501 秒延迟 ↓
- 0.36×CPU 时间 / 官方解 ↓
- 同阶 1时间复杂度(相对官方解)
↑ 越大越好,↓ 越小越好。得分 0–100,按官方时限判定,所有测试点都满分才算解出。CPU 时间 / 官方解为解出的答案在官方解最慢的 3 个测试点上的 CPU 时间之比(几何平均),只比较官方解至少需要 0.05 秒的题;复杂度按增长幂次相对官方解分类。判题与计分见 原理。
代码
#include <bits/stdc++.h> using namespace std; static const long long MOD = 1000000007LL; long long modpow(long long a, long long e) { long long r = 1; while (e) { if (e & 1) r = r * a % MOD; a = a * a % MOD; e >>= 1; } return r; } inline long long norm(long long x) { x %= MOD; if (x < 0) x += MOD; return x; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; vector<int> parent(N + 1), depth(N + 1); vector<vector<int>> children(N + 1); for (int v = 2; v <= N; ++v) { cin >> parent[v]; depth[v] = depth[parent[v]] + 1; children[parent[v]].push_back(v); } vector<long long> invInt(N + 1); invInt[1] = 1; for (int i = 2; i <= N; ++i) { invInt[i] = MOD - (MOD / i) * invInt[MOD % i] % MOD; } // If a subtree contains no special boundary node, its root value is // A[v] + B[v] * (sum of values of its proper ancestors). vector<long long> A(N + 1), B(N + 1); vector<long long> sumA(N + 1), sumB(N + 1); for (int v = N; v >= 2; --v) { if (children[v].empty()) { A[v] = 1; B[v] = invInt[depth[v]]; } else { long long d = (long long)children[v].size(); long long den = norm(d - sumB[v]); long long invDen = modpow(den, MOD - 2); A[v] = norm(d + sumA[v]) * invDen % MOD; B[v] = sumB[v] * invDen % MOD; } int p = parent[v]; sumA[p] = norm(sumA[p] + A[v]); sumB[p] = norm(sumB[p] + B[v]); } vector<long long> F(N + 1), SF(N + 1); // Hitting time of the root. vector<long long> U(N + 1), SU(N + 1); // Homogeneous path solution. vector<long long> R(N + 1), SR(N + 1); vector<long long> T(N + 1), ST(N + 1); vector<long long> prod(N + 1); R[1] = SR[1] = 1; prod[1] = 1; for (int v = 2; v <= N; ++v) { int u = parent[v]; long long d = (long long)children[u].size(); long long offA = norm(sumA[u] - A[v]); long long offB = norm(sumB[u] - B[v]); F[v] = norm(A[v] + B[v] * SF[u]); SF[v] = norm(SF[u] + F[v]); prod[v] = prod[u] * norm(1 + B[v]) % MOD; if (u == 1) { U[v] = 1; SU[v] = 1; } else { U[v] = norm(d * U[u] - offB * SU[u]); SU[v] = norm(SU[u] + U[v]); } R[v] = norm(d * R[u] - offB * SR[u]); T[v] = norm(d * T[u] - d - offA - offB * ST[u]); SR[v] = norm(SR[u] + R[v]); ST[v] = norm(ST[u] + T[v]); } vector<long long> invProd(N + 1), invU(N + 1), targetC(N + 1); for (int v = 1; v <= N; ++v) { invProd[v] = modpow(prod[v], MOD - 2); } for (int v = 2; v <= N; ++v) { invU[v] = modpow(U[v], MOD - 2); // Expected time from the root to v is -T[v]/R[v]. // targetC[v] = F[v] + that expected time. targetC[v] = norm(F[v] - T[v] * modpow(R[v], MOD - 2)); } int LOG = 1; while ((1 << LOG) <= N) ++LOG; vector<vector<int>> up(LOG, vector<int>(N + 1)); up[0][1] = 1; for (int v = 2; v <= N; ++v) up[0][v] = parent[v]; for (int k = 1; k < LOG; ++k) { for (int v = 1; v <= N; ++v) { up[k][v] = up[k - 1][up[k - 1][v]]; } } auto lca = [&](int a, int b) { if (depth[a] < depth[b]) swap(a, b); int diff = depth[a] - depth[b]; for (int k = 0; k < LOG; ++k) { if (diff & (1 << k)) a = up[k][a]; } if (a == b) return a; for (int k = LOG - 1; k >= 0; --k) { if (up[k][a] != up[k][b]) { a = up[k][a]; b = up[k][b]; } } return parent[a]; }; while (Q--) { int x, y; cin >> x >> y; if (x == y) { cout << 0 << '\n'; continue; } if (y == 1) { cout << F[x] << '\n'; continue; } int l = lca(x, y); long long r; // Probability of reaching y before the root. if (l == x) { // x is on the root-to-y path. r = U[x] * invU[y] % MOD; } else { long long k = B[x] * prod[parent[x]] % MOD; r = k * invProd[l] % MOD; r = r * SU[l] % MOD; r = r * invU[y] % MOD; } long long ans = norm( F[x] - F[y] + norm(1 - r) * targetC[y] ); cout << ans << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; static const int MOD = 1000000007; using int64 = long long; int modpow(int a, int e = MOD - 2) { int64 r = 1, x = a; while (e > 0) { if (e & 1) r = r * x % MOD; x = x * x % MOD; e >>= 1; } return (int)r; } // Transformation: z -> a*z + b*k + c (mod MOD). struct Aff { int a = 1, b = 0, c = 0; }; // Returns f(g(z)). Aff compose(const Aff &f, const Aff &g) { Aff h; h.a = (int64)f.a * g.a % MOD; h.b = ((int64)f.a * g.b + f.b) % MOD; h.c = ((int64)f.a * g.c + f.c) % MOD; return h; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; vector<int> parent(N + 1), depth(N + 1); vector<vector<int>> children(N + 1); for (int i = 2; i <= N; ++i) { cin >> parent[i]; children[parent[i]].push_back(i); depth[i] = depth[parent[i]] + 1; } vector<int> inv(N + 1); inv[1] = 1; for (int i = 2; i <= N; ++i) { inv[i] = (int64)(MOD - MOD / i) * inv[MOD % i] % MOD; } // For every non-root v: // H(v,target) = A[v] + B[v] * (sum of H at strict ancestors of v), // provided the target is outside subtree(v). vector<int> A(N + 1), B(N + 1); for (int v = N; v >= 2; --v) { if (children[v].empty()) { A[v] = 1; B[v] = inv[depth[v]]; continue; } int64 sumA = 0, sumB = 0; for (int c : children[v]) { sumA += A[c]; sumB += B[c]; } int k = (int)children[v].size(); int avgA = sumA % MOD * inv[k] % MOD; int avgB = sumB % MOD * inv[k] % MOD; int den = 1 - avgB; if (den < 0) den += MOD; int invDen = modpow(den); A[v] = (int64)(1 + avgA) * invDen % MOD; B[v] = (int64)avgB * invDen % MOD; } int LOG = 1; while ((1 << LOG) <= N) ++LOG; vector<vector<int>> up(LOG, vector<int>(N + 1)); for (int v = 2; v <= N; ++v) up[0][v] = parent[v]; for (int k = 1; k < LOG; ++k) { for (int v = 1; v <= N; ++v) { up[k][v] = up[k - 1][up[k - 1][v]]; } } // tr[k][v] describes the 2^k transformations on the path ending at v, // composed from top to bottom. vector<vector<Aff>> tr(LOG, vector<Aff>(N + 1)); for (int v = 2; v <= N; ++v) { tr[0][v] = {(B[v] + 1) % MOD, B[v], A[v]}; } for (int k = 1; k < LOG; ++k) { int len = 1 << k; for (int v = 2; v <= N; ++v) { if (depth[v] < len) continue; int mid = up[k - 1][v]; // Bottom half is applied after the top half. tr[k][v] = compose(tr[k - 1][v], tr[k - 1][mid]); } } // P[v]: expected time to reach v from the root. // C[v]: sum of expected hitting times to v from all strict ancestors of v. vector<int> P(N + 1), C(N + 1), ancestorSumP(N + 1), hitParent(N + 1); for (int v = 1; v <= N; ++v) { if (children[v].empty()) continue; int64 sumR = 0; for (int c : children[v]) { hitParent[c] = (A[c] + (int64)B[c] * C[v]) % MOD; sumR += hitParent[c]; } sumR %= MOD; int k = (int)children[v].size(); for (int c : children[v]) { int edgeTime = (k + sumR - hitParent[c]) % MOD; if (edgeTime < 0) edgeTime += MOD; P[c] = (P[v] + edgeTime) % MOD; ancestorSumP[c] = (ancestorSumP[v] + P[v]) % MOD; C[c] = ((int64)depth[c] * P[c] - ancestorSumP[c]) % MOD; if (C[c] < 0) C[c] += MOD; } } auto lca = [&](int a, int b) { if (depth[a] < depth[b]) swap(a, b); int diff = depth[a] - depth[b]; for (int k = LOG - 1; k >= 0; --k) { if ((diff >> k) & 1) a = up[k][a]; } if (a == b) return a; for (int k = LOG - 1; k >= 0; --k) { if (up[k][a] != up[k][b]) { a = up[k][a]; b = up[k][b]; } } return up[0][a]; }; // Sum of hitting values strictly between ancestor a and descendant x, // including parent(x), expressed using the boundary value C[a]. auto intermediateSum = [&](int x, int a) { int len = depth[x] - depth[a] - 1; if (len <= 0) return 0; int cur = parent[x]; Aff result; // identity for (int k = 0; k < LOG; ++k) { if ((len >> k) & 1) { // The new block is above all previously processed blocks. result = compose(result, tr[k][cur]); cur = up[k][cur]; } } return (int)(((int64)result.b * C[a] + result.c) % MOD); }; // Expected time to reach ancestor a from descendant x. auto hitAncestor = [&](int x, int a) { int z = intermediateSum(x, a); int total = C[a] + z; if (total >= MOD) total -= MOD; return (int)((A[x] + (int64)B[x] * total) % MOD); }; while (Q--) { int x, y; cin >> x >> y; int w = lca(x, y); int answer; if (w == y) { answer = (x == y) ? 0 : hitAncestor(x, y); } else if (w == x) { answer = P[y] - P[x]; if (answer < 0) answer += MOD; } else { answer = ((int64)hitAncestor(x, w) + P[y] - P[w]) % MOD; if (answer < 0) answer += MOD; } cout << answer << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; static const long long MOD = 1000000007LL; long long modpow(long long a, long long e = MOD - 2) { long long r = 1; while (e > 0) { if (e & 1) r = r * a % MOD; a = a * a % MOD; e >>= 1; } return r; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; vector<int> par(N + 1, 0), depth(N + 1, 0), deg(N + 1, 0); par[1] = 1; for (int v = 2; v <= N; ++v) { cin >> par[v]; depth[v] = depth[par[v]] + 1; ++deg[par[v]]; } vector<long long> invInt(N + 1, 0); invInt[1] = 1; for (int i = 2; i <= N; ++i) { invInt[i] = MOD - (MOD / i) * invInt[MOD % i] % MOD; } // For a node v, F_v = A[v] * P_parent(v) + B[v], where // P_v is the sum of F values on the root-to-v path. vector<long long> A(N + 1, 0), B(N + 1, 0); vector<long long> sumA(N + 1, 0), sumB(N + 1, 0); for (int v = N; v >= 2; --v) { if (deg[v] == 0) { A[v] = invInt[depth[v]]; B[v] = 1; } else { long long avgA = sumA[v] * invInt[deg[v]] % MOD; long long avgB = sumB[v] * invInt[deg[v]] % MOD; long long den = (1 - avgA + MOD) % MOD; long long invDen = modpow(den); A[v] = avgA * invDen % MOD; B[v] = (1 + avgB) % MOD * invDen % MOD; } int p = par[v]; sumA[p] = (sumA[p] + A[v]) % MOD; sumB[p] = (sumB[p] + B[v]) % MOD; } // G[v] = expected time to reach v starting from the root. // SG[v] = sum of G on the root-to-v path. vector<long long> G(N + 1, 0), SG(N + 1, 0); for (int v = 2; v <= N; ++v) { int p = par[v]; long long invC = invInt[deg[p]]; long long otherA = (sumA[p] - A[v] + MOD) % MOD; long long otherB = (sumB[p] - B[v] + MOD) % MOD; long long W = otherA * invC % MOD; long long Z = (1 + otherB * invC % MOD) % MOD; long long den = (1 - W * (depth[p] + 1LL) % MOD + MOD) % MOD; long long num = (G[p] - W * SG[p] % MOD + Z + MOD) % MOD; G[v] = num * modpow(den) % MOD; SG[v] = (SG[p] + G[v]) % MOD; } // S[a] is P_parent(a) when a is the target. vector<long long> S(N + 1, 0); for (int v = 2; v <= N; ++v) { S[v] = ((long long)depth[v] * G[v] - SG[par[v]]) % MOD; if (S[v] < 0) S[v] += MOD; } // Compositions of P_v = (1 + A[v]) * P_parent(v) + B[v]. vector<long long> M(N + 1, 0), K(N + 1, 0), invM(N + 1, 0); M[1] = 1; K[1] = 0; invM[1] = 1; for (int v = 2; v <= N; ++v) { int p = par[v]; long long u = (1 + A[v]) % MOD; M[v] = u * M[p] % MOD; K[v] = (u * K[p] + B[v]) % MOD; } for (int v = 2; v <= N; ++v) { invM[v] = modpow(M[v]); } int LOG = 1; while ((1 << LOG) <= N) ++LOG; vector<vector<int>> up(LOG, vector<int>(N + 1, 1)); for (int v = 2; v <= N; ++v) up[0][v] = par[v]; up[0][1] = 1; for (int j = 1; j < LOG; ++j) { for (int v = 1; v <= N; ++v) { up[j][v] = up[j - 1][up[j - 1][v]]; } } auto lca = [&](int a, int b) { if (depth[a] < depth[b]) swap(a, b); int diff = depth[a] - depth[b]; for (int j = LOG - 1; j >= 0; --j) { if (diff & (1 << j)) a = up[j][a]; } if (a == b) return a; for (int j = LOG - 1; j >= 0; --j) { if (up[j][a] != up[j][b]) { a = up[j][a]; b = up[j][b]; } } return up[0][a]; }; while (Q--) { int x, y; cin >> x >> y; int a = lca(x, y); long long answer = (G[y] - G[a] + MOD) % MOD; if (x != a) { // Expected time to go from x to its ancestor a. int px = par[x]; long long ratio = M[px] * invM[a] % MOD; long long P = (ratio * S[a] % MOD + K[px]) % MOD; P = (P - ratio * K[a] % MOD + MOD) % MOD; long long hittingTime = (A[x] * P + B[x]) % MOD; answer = (answer + hittingTime) % MOD; } cout << answer << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; static const long long MOD = 1000000007LL; long long modpow(long long a, long long e) { long long r = 1; while (e) { if (e & 1) r = r * a % MOD; a = a * a % MOD; e >>= 1; } return r; } inline long long norm(long long x) { x %= MOD; if (x < 0) x += MOD; return x; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; vector<int> parent(N + 1), depth(N + 1); vector<vector<int>> children(N + 1); for (int v = 2; v <= N; ++v) { cin >> parent[v]; depth[v] = depth[parent[v]] + 1; children[parent[v]].push_back(v); } vector<long long> invInt(N + 1); invInt[1] = 1; for (int i = 2; i <= N; ++i) { invInt[i] = MOD - (MOD / i) * invInt[MOD % i] % MOD; } // If a subtree contains no special boundary node, its root value is // A[v] + B[v] * (sum of values of its proper ancestors). vector<long long> A(N + 1), B(N + 1); vector<long long> sumA(N + 1), sumB(N + 1); for (int v = N; v >= 2; --v) { if (children[v].empty()) { A[v] = 1; B[v] = invInt[depth[v]]; } else { long long d = (long long)children[v].size(); long long den = norm(d - sumB[v]); long long invDen = modpow(den, MOD - 2); A[v] = norm(d + sumA[v]) * invDen % MOD; B[v] = sumB[v] * invDen % MOD; } int p = parent[v]; sumA[p] = norm(sumA[p] + A[v]); sumB[p] = norm(sumB[p] + B[v]); } vector<long long> F(N + 1), SF(N + 1); // Hitting time of the root. vector<long long> U(N + 1), SU(N + 1); // Homogeneous path solution. vector<long long> R(N + 1), SR(N + 1); vector<long long> T(N + 1), ST(N + 1); vector<long long> prod(N + 1); R[1] = SR[1] = 1; prod[1] = 1; for (int v = 2; v <= N; ++v) { int u = parent[v]; long long d = (long long)children[u].size(); long long offA = norm(sumA[u] - A[v]); long long offB = norm(sumB[u] - B[v]); F[v] = norm(A[v] + B[v] * SF[u]); SF[v] = norm(SF[u] + F[v]); prod[v] = prod[u] * norm(1 + B[v]) % MOD; if (u == 1) { U[v] = 1; SU[v] = 1; } else { U[v] = norm(d * U[u] - offB * SU[u]); SU[v] = norm(SU[u] + U[v]); } R[v] = norm(d * R[u] - offB * SR[u]); T[v] = norm(d * T[u] - d - offA - offB * ST[u]); SR[v] = norm(SR[u] + R[v]); ST[v] = norm(ST[u] + T[v]); } vector<long long> invProd(N + 1), invU(N + 1), targetC(N + 1); for (int v = 1; v <= N; ++v) { invProd[v] = modpow(prod[v], MOD - 2); } for (int v = 2; v <= N; ++v) { invU[v] = modpow(U[v], MOD - 2); // Expected time from the root to v is -T[v]/R[v]. // targetC[v] = F[v] + that expected time. targetC[v] = norm(F[v] - T[v] * modpow(R[v], MOD - 2)); } int LOG = 1; while ((1 << LOG) <= N) ++LOG; vector<vector<int>> up(LOG, vector<int>(N + 1)); up[0][1] = 1; for (int v = 2; v <= N; ++v) up[0][v] = parent[v]; for (int k = 1; k < LOG; ++k) { for (int v = 1; v <= N; ++v) { up[k][v] = up[k - 1][up[k - 1][v]]; } } auto lca = [&](int a, int b) { if (depth[a] < depth[b]) swap(a, b); int diff = depth[a] - depth[b]; for (int k = 0; k < LOG; ++k) { if (diff & (1 << k)) a = up[k][a]; } if (a == b) return a; for (int k = LOG - 1; k >= 0; --k) { if (up[k][a] != up[k][b]) { a = up[k][a]; b = up[k][b]; } } return parent[a]; }; while (Q--) { int x, y; cin >> x >> y; if (x == y) { cout << 0 << '\n'; continue; } if (y == 1) { cout << F[x] << '\n'; continue; } int l = lca(x, y); long long r; // Probability of reaching y before the root. if (l == x) { // x is on the root-to-y path. r = U[x] * invU[y] % MOD; } else { long long k = B[x] * prod[parent[x]] % MOD; r = k * invProd[l] % MOD; r = r * SU[l] % MOD; r = r * invU[y] % MOD; } long long ans = norm( F[x] - F[y] + norm(1 - r) * targetC[y] ); cout << ans << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; static const int MOD = 1000000007; using int64 = long long; int modpow(int a, int e = MOD - 2) { int64 r = 1, x = a; while (e > 0) { if (e & 1) r = r * x % MOD; x = x * x % MOD; e >>= 1; } return (int)r; } // Transformation: z -> a*z + b*k + c (mod MOD). struct Aff { int a = 1, b = 0, c = 0; }; // Returns f(g(z)). Aff compose(const Aff &f, const Aff &g) { Aff h; h.a = (int64)f.a * g.a % MOD; h.b = ((int64)f.a * g.b + f.b) % MOD; h.c = ((int64)f.a * g.c + f.c) % MOD; return h; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; vector<int> parent(N + 1), depth(N + 1); vector<vector<int>> children(N + 1); for (int i = 2; i <= N; ++i) { cin >> parent[i]; children[parent[i]].push_back(i); depth[i] = depth[parent[i]] + 1; } vector<int> inv(N + 1); inv[1] = 1; for (int i = 2; i <= N; ++i) { inv[i] = (int64)(MOD - MOD / i) * inv[MOD % i] % MOD; } // For every non-root v: // H(v,target) = A[v] + B[v] * (sum of H at strict ancestors of v), // provided the target is outside subtree(v). vector<int> A(N + 1), B(N + 1); for (int v = N; v >= 2; --v) { if (children[v].empty()) { A[v] = 1; B[v] = inv[depth[v]]; continue; } int64 sumA = 0, sumB = 0; for (int c : children[v]) { sumA += A[c]; sumB += B[c]; } int k = (int)children[v].size(); int avgA = sumA % MOD * inv[k] % MOD; int avgB = sumB % MOD * inv[k] % MOD; int den = 1 - avgB; if (den < 0) den += MOD; int invDen = modpow(den); A[v] = (int64)(1 + avgA) * invDen % MOD; B[v] = (int64)avgB * invDen % MOD; } int LOG = 1; while ((1 << LOG) <= N) ++LOG; vector<vector<int>> up(LOG, vector<int>(N + 1)); for (int v = 2; v <= N; ++v) up[0][v] = parent[v]; for (int k = 1; k < LOG; ++k) { for (int v = 1; v <= N; ++v) { up[k][v] = up[k - 1][up[k - 1][v]]; } } // tr[k][v] describes the 2^k transformations on the path ending at v, // composed from top to bottom. vector<vector<Aff>> tr(LOG, vector<Aff>(N + 1)); for (int v = 2; v <= N; ++v) { tr[0][v] = {(B[v] + 1) % MOD, B[v], A[v]}; } for (int k = 1; k < LOG; ++k) { int len = 1 << k; for (int v = 2; v <= N; ++v) { if (depth[v] < len) continue; int mid = up[k - 1][v]; // Bottom half is applied after the top half. tr[k][v] = compose(tr[k - 1][v], tr[k - 1][mid]); } } // P[v]: expected time to reach v from the root. // C[v]: sum of expected hitting times to v from all strict ancestors of v. vector<int> P(N + 1), C(N + 1), ancestorSumP(N + 1), hitParent(N + 1); for (int v = 1; v <= N; ++v) { if (children[v].empty()) continue; int64 sumR = 0; for (int c : children[v]) { hitParent[c] = (A[c] + (int64)B[c] * C[v]) % MOD; sumR += hitParent[c]; } sumR %= MOD; int k = (int)children[v].size(); for (int c : children[v]) { int edgeTime = (k + sumR - hitParent[c]) % MOD; if (edgeTime < 0) edgeTime += MOD; P[c] = (P[v] + edgeTime) % MOD; ancestorSumP[c] = (ancestorSumP[v] + P[v]) % MOD; C[c] = ((int64)depth[c] * P[c] - ancestorSumP[c]) % MOD; if (C[c] < 0) C[c] += MOD; } } auto lca = [&](int a, int b) { if (depth[a] < depth[b]) swap(a, b); int diff = depth[a] - depth[b]; for (int k = LOG - 1; k >= 0; --k) { if ((diff >> k) & 1) a = up[k][a]; } if (a == b) return a; for (int k = LOG - 1; k >= 0; --k) { if (up[k][a] != up[k][b]) { a = up[k][a]; b = up[k][b]; } } return up[0][a]; }; // Sum of hitting values strictly between ancestor a and descendant x, // including parent(x), expressed using the boundary value C[a]. auto intermediateSum = [&](int x, int a) { int len = depth[x] - depth[a] - 1; if (len <= 0) return 0; int cur = parent[x]; Aff result; // identity for (int k = 0; k < LOG; ++k) { if ((len >> k) & 1) { // The new block is above all previously processed blocks. result = compose(result, tr[k][cur]); cur = up[k][cur]; } } return (int)(((int64)result.b * C[a] + result.c) % MOD); }; // Expected time to reach ancestor a from descendant x. auto hitAncestor = [&](int x, int a) { int z = intermediateSum(x, a); int total = C[a] + z; if (total >= MOD) total -= MOD; return (int)((A[x] + (int64)B[x] * total) % MOD); }; while (Q--) { int x, y; cin >> x >> y; int w = lca(x, y); int answer; if (w == y) { answer = (x == y) ? 0 : hitAncestor(x, y); } else if (w == x) { answer = P[y] - P[x]; if (answer < 0) answer += MOD; } else { answer = ((int64)hitAncestor(x, w) + P[y] - P[w]) % MOD; if (answer < 0) answer += MOD; } cout << answer << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; static const int MOD = 1000000007; struct Mat { int a = 1, b = 0, c = 0, d = 1; }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; vector<int> parent(N + 1), depth(N + 1), deg(N + 1, 0); for (int v = 2; v <= N; ++v) { cin >> parent[v]; depth[v] = depth[parent[v]] + 1; ++deg[parent[v]]; } vector<int> inv(N + 2, 1); for (int i = 2; i <= N + 1; ++i) { inv[i] = int((MOD - 1LL * (MOD / i) * inv[MOD % i]) % MOD); } // Effective cost of each subtree. vector<int> cost(N + 1, 0), sumCost(N + 1, 0); for (int v = N; v >= 2; --v) { if (deg[v] == 0) { cost[v] = 1; } else { long long inside = (1 + 1LL * sumCost[v] * inv[deg[v]]) % MOD; cost[v] = int(1LL * (depth[v] + 1) * inv[depth[v]] % MOD * inside % MOD); } int p = parent[v]; sumCost[p] = (sumCost[p] + cost[v]) % MOD; } // R[v] = expected time to reach the root from v. vector<int> R(N + 1, 0), ancestorSum(N + 1, 0); long long K = deg[1]; for (int v = 2; v <= N; ++v) { int p = parent[v]; ancestorSum[v] = (ancestorSum[p] + R[p]) % MOD; R[v] = (cost[v] + 1LL * ancestorSum[v] * inv[depth[v]]) % MOD; if (p == 1) K += R[v]; } K %= MOD; int LOG = 1; while ((1 << LOG) <= N) ++LOG; vector<vector<int>> up(LOG, vector<int>(N + 1, 1)); up[0][1] = 1; for (int v = 2; v <= N; ++v) up[0][v] = parent[v]; for (int j = 1; j < LOG; ++j) { for (int v = 1; v <= N; ++v) { up[j][v] = up[j - 1][up[j - 1][v]]; } } auto multiply = [](const Mat &A, const Mat &B) { Mat r; r.a = int((1LL * A.a * B.a + 1LL * A.b * B.c) % MOD); r.b = int((1LL * A.a * B.b + 1LL * A.b * B.d) % MOD); r.c = int((1LL * A.c * B.a + 1LL * A.d * B.c) % MOD); r.d = int((1LL * A.c * B.b + 1LL * A.d * B.d) % MOD); return r; }; // jumpMat[j][v]: transformation over a path segment of length 2^j ending at v. vector<vector<Mat>> jumpMat(LOG, vector<Mat>(N + 1)); for (int v = 2; v <= N; ++v) { if (depth[v] < 2) continue; int u = parent[v]; int i = depth[u]; long long d = deg[u]; Mat m; m.a = int((d * i + 1) % MOD * inv[i + 1] % MOD); m.b = (d == 1 ? 0 : int((MOD - (d - 1) * inv[i + 1] % MOD) % MOD)); m.c = 1; m.d = 1; jumpMat[0][v] = m; } for (int j = 1; j < LOG; ++j) { int len = 1 << j; for (int v = 1; v <= N; ++v) { if (len > depth[v] - 1) continue; int mid = up[j - 1][v]; jumpMat[j][v] = multiply(jumpMat[j - 1][v], jumpMat[j - 1][mid]); } } auto getTransform = [&](int v) { Mat result; int len = depth[v] - 1; for (int j = 0; j < LOG; ++j) { if ((len >> j) & 1) { result = multiply(result, jumpMat[j][v]); v = up[j][v]; } } return result; }; auto lca = [&](int a, int b) { if (depth[a] < depth[b]) swap(a, b); int diff = depth[a] - depth[b]; for (int j = 0; j < LOG; ++j) { if ((diff >> j) & 1) a = up[j][a]; } if (a == b) return a; for (int j = LOG - 1; j >= 0; --j) { if (up[j][a] != up[j][b]) { a = up[j][a]; b = up[j][b]; } } return up[0][a]; }; auto modPow = [](long long a, long long e) { long long r = 1; while (e) { if (e & 1) r = r * a % MOD; a = a * a % MOD; e >>= 1; } return int(r); }; while (Q--) { int x, y; cin >> x >> y; if (y == 1) { cout << R[x] << '\n'; continue; } Mat targetTransform = getTransform(y); long long den = (targetTransform.a + targetTransform.b) % MOD; long long targetD = (MOD - R[y]) % MOD; long long rhs = (targetD - 1LL * targetTransform.b * K) % MOD; if (rhs < 0) rhs += MOD; long long D1 = rhs * modPow(den, MOD - 2) % MOD; long long D0 = (D1 + K) % MOD; int z = lca(x, y); if (z == x) { // x lies on the root-to-y path. if (x == 1) { cout << D0 << '\n'; } else if (x == y) { cout << 0 << '\n'; } else { Mat m = getTransform(x); long long D = (1LL * m.a * D1 + 1LL * m.b * D0) % MOD; cout << (R[x] + D) % MOD << '\n'; } } else { // x is in an off-path branch attached at z. if (z == 1) { cout << (R[x] + D0) % MOD << '\n'; } else { Mat m = getTransform(z); long long D = (1LL * m.a * D1 + 1LL * m.b * D0) % MOD; long long T = (1LL * m.c * D1 + 1LL * m.d * D0) % MOD; long long delta = (D + T) % MOD * inv[depth[z] + 1] % MOD; cout << (R[x] + delta) % MOD << '\n'; } } } return 0; }
#include <bits/stdc++.h> using namespace std; static const int MOD = 1000000007; static const int LOG = 20; struct Aff { // F' = a*F + b*S + e // S' = c*F + d*S + f int a, b, c, d, e, f; }; static const Aff ID = {1, 0, 0, 1, 0, 0}; int N, Q; vector<int> parentNode, depthNode, childCnt, eVal, Atot, invs; vector<vector<int>> up; vector<vector<Aff>> liftMat; vector<Aff> prodRoot; Aff compose(const Aff& A, const Aff& B) { // Returns A after B: A(B(x)) Aff C; C.a = (1LL * A.a * B.a + 1LL * A.b * B.c) % MOD; C.b = (1LL * A.a * B.b + 1LL * A.b * B.d) % MOD; C.c = (1LL * A.c * B.a + 1LL * A.d * B.c) % MOD; C.d = (1LL * A.c * B.b + 1LL * A.d * B.d) % MOD; C.e = (1LL * A.a * B.e + 1LL * A.b * B.f + A.e) % MOD; C.f = (1LL * A.c * B.e + 1LL * A.d * B.f + A.f) % MOD; return C; } int liftNode(int v, int k) { for (int j = 0; j < LOG; j++) { if ((k >> j) & 1) v = up[j][v]; } return v; } int getLCA(int u, int v) { if (depthNode[u] < depthNode[v]) swap(u, v); u = liftNode(u, depthNode[u] - depthNode[v]); if (u == v) return u; for (int j = LOG - 1; j >= 0; j--) { if (up[j][u] != up[j][v]) { u = up[j][u]; v = up[j][v]; } } return up[0][u]; } int queryDescendant(int c, int x, int Fc, int Sc) { Aff res = ID; int cur = x; int diff = depthNode[x] - depthNode[c]; for (int j = 0; j < LOG; j++) { if ((diff >> j) & 1) { res = compose(res, liftMat[j][cur]); cur = up[j][cur]; } } long long ans = 1LL * res.a * Fc + 1LL * res.b * Sc + res.e; ans %= MOD; return (int)ans; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cin >> N >> Q; parentNode.assign(N + 1, 0); depthNode.assign(N + 1, 0); childCnt.assign(N + 1, 0); for (int i = 2; i <= N; i++) { int p; cin >> p; parentNode[i] = p; depthNode[i] = depthNode[p] + 1; childCnt[p]++; } invs.assign(N + 2, 1); for (int i = 2; i <= N + 1; i++) { invs[i] = MOD - 1LL * (MOD / i) * invs[MOD % i] % MOD; } eVal.assign(N + 1, 0); Atot.assign(N + 1, 0); vector<int> sumE(N + 1, 0); for (int u = N; u >= 2; u--) { Atot[u] = sumE[u]; int d = depthNode[u]; if (childCnt[u] == 0) { eVal[u] = 1; } else { long long val = (childCnt[u] + sumE[u]) % MOD; eVal[u] = val * (d + 1) % MOD * invs[childCnt[u]] % MOD * invs[d] % MOD; } sumE[parentNode[u]] += eVal[u]; if (sumE[parentNode[u]] >= MOD) sumE[parentNode[u]] -= MOD; } Atot[1] = sumE[1]; prodRoot.assign(N + 1, ID); prodRoot[1] = ID; for (int v = 2; v <= N; v++) { int u = parentNode[v]; int d = depthNode[u]; int cnt = childCnt[u]; int invd1 = invs[d + 1]; int Btot = 1LL * cnt * invd1 % MOD; int Bv = invd1; int a00 = (cnt - Btot + Bv) % MOD; if (a00 < 0) a00 += MOD; int a01 = (Bv - Btot) % MOD; if (a01 < 0) a01 += MOD; int val = (cnt + Atot[u]) % MOD; val = (val - eVal[v]) % MOD; if (val < 0) val += MOD; int a02 = (val == 0 ? 0 : MOD - val); Aff edge = {a00, a01, 1, 1, a02, 0}; prodRoot[v] = compose(edge, prodRoot[u]); } up.assign(LOG, vector<int>(N + 1, 0)); liftMat.assign(LOG, vector<Aff>(N + 1, ID)); up[0][0] = 0; liftMat[0][0] = ID; for (int v = 1; v <= N; v++) { if (v == 1) { up[0][v] = 0; liftMat[0][v] = ID; } else { up[0][v] = parentNode[v]; int Bv = invs[depthNode[v]]; int Av = eVal[v]; liftMat[0][v] = {Bv, Bv, 1, 1, Av, 0}; } } for (int j = 1; j < LOG; j++) { for (int v = 0; v <= N; v++) { int mid = up[j - 1][v]; up[j][v] = up[j - 1][mid]; liftMat[j][v] = compose(liftMat[j - 1][v], liftMat[j - 1][mid]); } } while (Q--) { int x, y; cin >> x >> y; if (x == y) { cout << 0 << '\n'; continue; } Aff target = prodRoot[y]; // For target y, the value at the root is -constant term. int F0 = (target.e == 0 ? 0 : MOD - target.e); int lca = getLCA(x, y); Aff atL = prodRoot[lca]; int FL = (1LL * atL.a * F0 + atL.e) % MOD; int PL = (1LL * atL.c * F0 + atL.f) % MOD; int ans; if (lca == x) { // x is an ancestor of y. ans = FL; } else if (lca == y) { // y is an ancestor of x. int dist = depthNode[x] - depthNode[y]; int c = liftNode(x, dist - 1); int Sc = (PL + FL) % MOD; int invd = invs[depthNode[c]]; int Fc = (eVal[c] + 1LL * invd * Sc) % MOD; ans = queryDescendant(c, x, Fc, Sc); } else { // x and y are in different branches below lca. int dist = depthNode[x] - depthNode[lca]; int c = liftNode(x, dist - 1); int Sc = (PL + FL) % MOD; int invd = invs[depthNode[c]]; int Fc = (eVal[c] + 1LL * invd * Sc) % MOD; ans = queryDescendant(c, x, Fc, Sc); } cout << ans % MOD << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; static const int MOD = 1000000007; static const int MAXN = 200005; static const int LG = 20; int N, Q; int parentNode[MAXN], depthNode[MAXN], childCnt[MAXN]; int Bval[MAXN], sumB[MAXN]; int invNum[MAXN]; int alphaCoef[MAXN], betaCoef[MAXN], gammaCoef[MAXN], deltaCoef[MAXN]; int qMul[MAXN], qAdd[MAXN], qInv[MAXN]; int up[LG][MAXN]; // Projective transformation: // A' = (a A + b) / (c A + d) // B' = (e A + B + g) / (c A + d) int pa[LG][MAXN], pb[LG][MAXN], pc[LG][MAXN]; int pd[LG][MAXN], pe[LG][MAXN], pg[LG][MAXN]; struct Trans { int a, b, c, d, e, g; }; inline Trans combine(const Trans &L, const Trans &U) { // Apply L first, then U. Trans R; R.a = ((long long)U.a * L.a + (long long)U.b * L.c) % MOD; R.b = ((long long)U.a * L.b + (long long)U.b * L.d) % MOD; R.c = ((long long)U.c * L.a + (long long)U.d * L.c) % MOD; R.d = ((long long)U.c * L.b + (long long)U.d * L.d) % MOD; R.e = ((long long)U.e * L.a + (long long)U.g * L.c + L.e) % MOD; R.g = ((long long)U.e * L.b + (long long)U.g * L.d + L.g) % MOD; return R; } int modpow(long long a, long long e) { long long r = 1; a %= MOD; while (e > 0) { if (e & 1) r = r * a % MOD; a = a * a % MOD; e >>= 1; } return (int)r; } int liftNode(int u, int dist) { for (int k = 0; k < LG; k++) { if (dist & (1 << k)) u = up[k][u]; } return u; } int lca(int u, int v) { if (depthNode[u] < depthNode[v]) swap(u, v); u = liftNode(u, depthNode[u] - depthNode[v]); if (u == v) return u; for (int k = LG - 1; k >= 0; k--) { if (up[k][u] != up[k][v]) { u = up[k][u]; v = up[k][v]; } } return parentNode[u]; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cin >> N >> Q; parentNode[1] = 1; depthNode[1] = 0; for (int i = 2; i <= N; i++) { int p; cin >> p; parentNode[i] = p; depthNode[i] = depthNode[p] + 1; childCnt[p]++; } invNum[1] = 1; for (int i = 2; i <= N + 2; i++) { invNum[i] = MOD - (long long)(MOD / i) * invNum[MOD % i] % MOD; } // Compute base B values bottom-up. for (int v = N; v >= 2; v--) { if (childCnt[v] == 0) { Bval[v] = 1; } else { long long inside = (1 + (long long)sumB[v] * invNum[childCnt[v]]) % MOD; Bval[v] = (long long)(depthNode[v] + 1) * invNum[depthNode[v]] % MOD * inside % MOD; } sumB[parentNode[v]] += Bval[v]; if (sumB[parentNode[v]] >= MOD) sumB[parentNode[v]] -= MOD; } // Identity transformation for root. for (int k = 0; k < LG; k++) { up[k][1] = 1; pa[k][1] = 1; pb[k][1] = 0; pc[k][1] = 0; pd[k][1] = 1; pe[k][1] = 0; pg[k][1] = 0; } // Edge transformations for special path messages. for (int i = 2; i <= N; i++) { int v = parentNode[i]; int k = childCnt[v]; int d = depthNode[v]; int OA = (long long)(k - 1) * invNum[d + 1] % MOD; int OB = sumB[v] - Bval[i]; if (OB < 0) OB += MOD; up[0][i] = v; pa[0][i] = 1; pb[0][i] = OA; pc[0][i] = MOD - 1; // -1 pd[0][i] = (k - OA) % MOD; if (pd[0][i] < 0) pd[0][i] += MOD; pe[0][i] = 0; pg[0][i] = (k + OB) % MOD; } // Build binary lifting for special path transformations. for (int k = 1; k < LG; k++) { for (int v = 1; v <= N; v++) { int anc = up[k - 1][v]; up[k][v] = up[k - 1][anc]; Trans L{pa[k - 1][v], pb[k - 1][v], pc[k - 1][v], pd[k - 1][v], pe[k - 1][v], pg[k - 1][v]}; Trans U{pa[k - 1][anc], pb[k - 1][anc], pc[k - 1][anc], pd[k - 1][anc], pe[k - 1][anc], pg[k - 1][anc]}; Trans R = combine(L, U); pa[k][v] = R.a; pb[k][v] = R.b; pc[k][v] = R.c; pd[k][v] = R.d; pe[k][v] = R.e; pg[k][v] = R.g; } } // Coefficients expressing s_v and f_v as affine functions of f_root. alphaCoef[1] = 0; betaCoef[1] = 0; gammaCoef[1] = 1; deltaCoef[1] = 0; for (int i = 2; i <= N; i++) { int v = parentNode[i]; int k = childCnt[v]; int OA = pb[0][i]; int OB = sumB[v] - Bval[i]; if (OB < 0) OB += MOD; int kOA = (k - OA) % MOD; if (kOA < 0) kOA += MOD; alphaCoef[i] = alphaCoef[v] + gammaCoef[v]; if (alphaCoef[i] >= MOD) alphaCoef[i] -= MOD; betaCoef[i] = betaCoef[v] + deltaCoef[v]; if (betaCoef[i] >= MOD) betaCoef[i] -= MOD; long long gv = (long long)kOA * gammaCoef[v] % MOD - (long long)OA * alphaCoef[v] % MOD; gv %= MOD; if (gv < 0) gv += MOD; gammaCoef[i] = gv; long long dv = (long long)kOA * deltaCoef[v] % MOD - (long long)OA * betaCoef[v] % MOD - (k + OB) % MOD; dv %= MOD; if (dv < 0) dv += MOD; deltaCoef[i] = dv; } // Base transformations for ordinary off-special subtrees. qMul[1] = 1; qAdd[1] = 0; qInv[1] = 1; for (int i = 2; i <= N; i++) { int v = parentNode[i]; if (v == 1) { qMul[i] = 1; qAdd[i] = 0; qInv[i] = 1; } else { int d = depthNode[v]; long long av = (long long)(d + 1) * invNum[d] % MOD; qMul[i] = av * qMul[v] % MOD; qAdd[i] = (av * qAdd[v] + Bval[v]) % MOD; long long invAv = (long long)d * invNum[d + 1] % MOD; qInv[i] = (long long)qInv[v] * invAv % MOD; } } while (Q--) { int x, y; cin >> x >> y; int z = lca(x, y); int A = 0; int Bspecial = 0; if (z != y) { int dist = depthNode[y] - depthNode[z]; Trans M{1, 0, 0, 1, 0, 0}; int cur = y; for (int k = 0; k < LG; k++) { if (dist & (1 << k)) { Trans Block{pa[k][cur], pb[k][cur], pc[k][cur], pd[k][cur], pe[k][cur], pg[k][cur]}; M = combine(M, Block); cur = up[k][cur]; } } int invD = modpow(M.d, MOD - 2); A = (long long)M.b * invD % MOD; Bspecial = (long long)M.g * invD % MOD; } long long den = gammaCoef[z] - (long long)A * alphaCoef[z] % MOD; den %= MOD; if (den < 0) den += MOD; long long num = (long long)A * betaCoef[z] % MOD + Bspecial - deltaCoef[z]; num %= MOD; if (num < 0) num += MOD; int Froot = (long long)num * modpow(den, MOD - 2) % MOD; int sz = ((long long)alphaCoef[z] * Froot + betaCoef[z]) % MOD; int fz = ((long long)A * sz + Bspecial) % MOD; int ans; if (x == z) { ans = fz; } else { int steps = depthNode[x] - depthNode[z] - 1; int c = liftNode(x, steps); int sc = sz + fz; if (sc >= MOD) sc -= MOD; int sprime = sc - qAdd[c]; if (sprime < 0) sprime += MOD; sprime = (long long)sprime * qInv[c] % MOD; int sx = ((long long)qMul[x] * sprime + qAdd[x]) % MOD; ans = ((long long)invNum[depthNode[x]] * sx + Bval[x]) % MOD; } cout << ans << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; static const int MOD = 1000000007; static const int MAXN = 200005; static const int LOG = 20; int parentNode[MAXN], depthNode[MAXN], childCount[MAXN]; int upTable[LOG][MAXN]; int invv[MAXN]; long long F[MAXN], sumF[MAXN], A[MAXN], invq[MAXN]; long long baseS[MAXN], P1[MAXN], P2[MAXN]; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; parentNode[1] = 1; depthNode[1] = 0; for (int i = 2; i <= N; i++) { cin >> parentNode[i]; depthNode[i] = depthNode[parentNode[i]] + 1; childCount[parentNode[i]]++; } int maxInv = N + 2; invv[1] = 1; for (int i = 2; i <= maxInv; i++) { invv[i] = MOD - (long long)(MOD / i) * invv[MOD % i] % MOD; } long long inv2 = invv[2]; // Compute F[u] = expected value of C(leaf) when descending from u. for (int i = N; i >= 1; i--) { if (childCount[i] == 0) { long long d = depthNode[i]; long long val = (d % MOD) * ((d + 3) % MOD) % MOD * inv2 % MOD; F[i] = (MOD - val) % MOD; } else { F[i] = sumF[i] * invv[childCount[i]] % MOD; } if (i > 1) { sumF[parentNode[i]] += F[i]; if (sumF[parentNode[i]] >= MOD) sumF[parentNode[i]] -= MOD; } } long long Froot = F[1]; invq[1] = 1; A[1] = Froot; baseS[1] = P1[1] = P2[1] = 0; for (int i = 2; i <= N; i++) { int p = parentNode[i]; invq[i] = invq[p] * childCount[p] % MOD; A[i] = Froot * invq[i] % MOD; int d = depthNode[i]; long long invd = invv[d]; long long edgeBase = (F[p] - F[i] + MOD) % MOD * invd % MOD; baseS[i] = (baseS[p] + edgeBase) % MOD; P1[i] = (P1[p] + A[i] * invd) % MOD; P2[i] = (P2[p] + A[p] * invd) % MOD; } for (int i = 1; i <= N; i++) { upTable[0][i] = parentNode[i]; } for (int k = 1; k < LOG; k++) { for (int i = 1; i <= N; i++) { upTable[k][i] = upTable[k - 1][upTable[k - 1][i]]; } } while (Q--) { int x, y; cin >> x >> y; int u = x, v = y; if (depthNode[u] < depthNode[v]) swap(u, v); int diff = depthNode[u] - depthNode[v]; for (int k = 0; k < LOG; k++) { if (diff & (1 << k)) { u = upTable[k][u]; } } int lca; if (u == v) { lca = u; } else { for (int k = LOG - 1; k >= 0; k--) { if (upTable[k][u] != upTable[k][v]) { u = upTable[k][u]; v = upTable[k][v]; } } lca = upTable[0][u]; } long long ans = 0; ans += (long long)depthNode[y] - depthNode[x]; ans += baseS[x] - baseS[y]; ans += P1[lca] - P2[lca]; ans -= P1[y] - P2[y]; if (x != lca) { int dl = depthNode[lca]; ans -= A[lca] * invv[dl + 1] % MOD; } ans %= MOD; if (ans < 0) ans += MOD; cout << ans << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; static constexpr int MOD = 1'000'000'007; static constexpr int LOG = 20; int modPow(int a, int e) { long long result = 1; long long base = a; while (e > 0) { if (e & 1) result = result * base % MOD; base = base * base % MOD; e >>= 1; } return static_cast<int>(result); } int normalize(long long x) { x %= MOD; if (x < 0) x += MOD; return static_cast<int>(x); } int multiply(int a, int b) { return static_cast<int>(1LL * a * b % MOD); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, Q; cin >> N >> Q; vector<int> parent(N + 1, 0); vector<int> depth(N + 1, 0); vector<int> childCount(N + 1, 0); vector<int> head(N + 1, -1); vector<int> nextSibling(N + 1, -1); for (int v = 2; v <= N; ++v) { cin >> parent[v]; depth[v] = depth[parent[v]] + 1; ++childCount[parent[v]]; nextSibling[v] = head[parent[v]]; head[parent[v]] = v; } vector<int> inverse(N + 1, 1); inverse[0] = 0; for (int i = 2; i <= N; ++i) { inverse[i] = MOD - static_cast<int>(1LL * (MOD / i) * inverse[MOD % i] % MOD); } /* For a target-free subtree, summarize: S[v] = messageA[v] * S[parent[v]] + messageB[v], where S[v] is the sum of expected hitting times over the ancestors of v, including v itself. */ vector<int> messageA(N + 1, 0); vector<int> messageB(N + 1, 0); vector<int> sumA(N + 1, 0); vector<int> sumB(N + 1, 0); for (int v = N; v >= 1; --v) { if (childCount[v] == 0) { int d = depth[v]; messageA[v] = multiply(d + 1, inverse[d]); messageB[v] = 1; } else { int averageA = multiply(sumA[v], inverse[childCount[v]]); int averageB = multiply(sumB[v], inverse[childCount[v]]); int denominator = normalize(2LL - averageA); // The root's own message is never needed. if (v != 1) { messageA[v] = modPow(denominator, MOD - 2); messageB[v] = multiply(messageA[v], normalize(1LL + averageB)); } } if (parent[v] != 0) { sumA[parent[v]] += messageA[v]; if (sumA[parent[v]] >= MOD) sumA[parent[v]] -= MOD; sumB[parent[v]] += messageB[v]; if (sumB[parent[v]] >= MOD) sumB[parent[v]] -= MOD; } } /* Along a root-to-target path, for an edge p -> c: S[c] = edgeC[c] * S[p] - childCount[p] * S[parent[p]] + edgeD[c]. */ vector<int> edgeC(N + 1, 0); vector<int> edgeD(N + 1, 0); for (int v = 2; v <= N; ++v) { int p = parent[v]; int sideA = normalize(1LL * sumA[p] - messageA[v]); int sideB = normalize(1LL * sumB[p] - messageB[v]); edgeC[v] = normalize(2LL * childCount[p] - sideA); edgeD[v] = normalize(-1LL * (childCount[p] + sideB)); } /* On any root-to-target path: S[v] = pathA[v] * S[root] + pathB[v]. */ vector<int> pathA(N + 1, 0); vector<int> pathB(N + 1, 0); pathA[1] = 1; for (int v = 2; v <= N; ++v) { int p = parent[v]; int pp = parent[p]; pathA[v] = normalize( 1LL * edgeC[v] * pathA[p] - 1LL * childCount[p] * pathA[pp] ); pathB[v] = normalize( 1LL * edgeC[v] * pathB[p] - 1LL * childCount[p] * pathB[pp] + edgeD[v] ); } /* If the target is y != root, then S[y] = S[parent[y]]. Solve for S[root] simultaneously for every possible target. */ vector<int> denominator(N + 1, 0); vector<int> numerator(N + 1, 0); vector<int> inverseDenominator(N + 1, 0); vector<int> rootValue(N + 1, 0); for (int y = 2; y <= N; ++y) { int p = parent[y]; denominator[y] = normalize(1LL * pathA[y] - pathA[p]); numerator[y] = normalize(1LL * pathB[p] - pathB[y]); } // Batch inversion of the target-path denominators. vector<int> prefix(N + 1, 1); for (int y = 2; y <= N; ++y) { int factor = denominator[y] == 0 ? 1 : denominator[y]; prefix[y] = multiply(prefix[y - 1], factor); } int inverseProduct = modPow(prefix[N], MOD - 2); for (int y = N; y >= 2; --y) { if (denominator[y] != 0) { inverseDenominator[y] = multiply(inverseProduct, prefix[y - 1]); inverseProduct = multiply(inverseProduct, denominator[y]); } } for (int y = 2; y <= N; ++y) { rootValue[y] = multiply(numerator[y], inverseDenominator[y]); } /* Binary lifting with affine compositions. affineA[k][v], affineB[k][v] satisfy: S[v] = affineA[k][v] * S[up[k][v]] + affineB[k][v]. */ vector<vector<int>> up(LOG, vector<int>(N + 1, 0)); vector<vector<int>> affineA(LOG, vector<int>(N + 1, 1)); vector<vector<int>> affineB(LOG, vector<int>(N + 1, 0)); for (int v = 1; v <= N; ++v) { up[0][v] = parent[v]; } for (int v = 2; v <= N; ++v) { affineA[0][v] = messageA[v]; affineB[0][v] = messageB[v]; } for (int k = 1; k < LOG; ++k) { for (int v = 1; v <= N; ++v) { int middle = up[k - 1][v]; up[k][v] = up[k - 1][middle]; int firstA = affineA[k - 1][v]; int firstB = affineB[k - 1][v]; int secondA = affineA[k - 1][middle]; int secondB = affineB[k - 1][middle]; affineA[k][v] = multiply(firstA, secondA); affineB[k][v] = normalize( 1LL * firstA * secondB + firstB ); } } // Subtree sizes and DFS order, computed without recursion. vector<int> subtreeSize(N + 1, 1); for (int v = N; v >= 2; --v) { subtreeSize[parent[v]] += subtreeSize[v]; } vector<int> tin(N + 1, 0); vector<int> stack; stack.reserve(N); stack.push_back(1); int timer = 0; while (!stack.empty()) { int v = stack.back(); stack.pop_back(); tin[v] = timer++; for (int c = head[v]; c != -1; c = nextSibling[c]) { stack.push_back(c); } } auto isAncestor = [&](int u, int v) -> bool { return tin[u] <= tin[v] && tin[v] < tin[u] + subtreeSize[u]; }; auto lca = [&](int u, int v) -> int { if (depth[u] < depth[v]) swap(u, v); int difference = depth[u] - depth[v]; for (int k = 0; k < LOG; ++k) { if ((difference >> k) & 1) { u = up[k][u]; } } if (u == v) return u; for (int k = LOG - 1; k >= 0; --k) { if (up[k][u] != up[k][v]) { u = up[k][u]; v = up[k][v]; } } return parent[u]; }; // Evaluate S[v] in a target-free subtree given S[top]. auto evaluateDown = [&](int top, int v, int topValue) -> int { if (v == top) return topValue; int distance = depth[v] - depth[top]; int current = v; long long coefficient = 1; long long constant = 0; for (int k = LOG - 1; k >= 0; --k) { if ((distance >> k) & 1) { int blockA = affineA[k][current]; int blockB = affineB[k][current]; int middle = up[k][current]; constant = (coefficient * blockB + constant) % MOD; coefficient = coefficient * blockA % MOD; current = middle; } } return static_cast<int>( (coefficient * topValue + constant) % MOD ); }; auto evaluateOnPath = [&](int v, int root) -> int { return normalize(1LL * pathA[v] * root + pathB[v]); }; while (Q--) { int x, y; cin >> x >> y; if (x == y) { cout << 0 << '\n'; continue; } int answer; if (y == 1) { // The target is the root, so S[root] = 0. int parentValue = evaluateDown(1, parent[x], 0); int xValue = normalize( 1LL * messageA[x] * parentValue + messageB[x] ); answer = normalize(xValue - parentValue); } else { int root = rootValue[y]; if (isAncestor(x, y)) { int xValue = evaluateOnPath(x, root); int parentValue = (x == 1 ? 0 : evaluateOnPath(parent[x], root)); answer = normalize(xValue - parentValue); } else { int top; int topValue; if (isAncestor(y, x)) { top = y; topValue = evaluateOnPath(top, root); } else { top = lca(x, y); topValue = evaluateOnPath(top, root); } int parentValue = evaluateDown(top, parent[x], topValue); int xValue = normalize( 1LL * messageA[x] * parentValue + messageB[x] ); answer = normalize(xValue - parentValue); } } cout << answer << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; static constexpr int MOD = 1'000'000'007; class FastScanner { static constexpr int SZ = 1 << 20; char buf[SZ]; int pos = 0, len = 0; inline int getChar() { if (pos == len) { len = (int)fread(buf, 1, SZ, stdin); pos = 0; if (!len) return EOF; } return buf[pos++]; } public: bool readInt(int &x) { int c; do { c = getChar(); if (c == EOF) return false; } while (c <= ' '); x = 0; while (c >= '0' && c <= '9') { x = x * 10 + (c - '0'); c = getChar(); } return true; } }; inline int addmod(int a, int b) { int s = a + b; if (s >= MOD) s -= MOD; return s; } inline int submod(int a, int b) { int s = a - b; if (s < 0) s += MOD; return s; } inline int modPow(int a, int e) { int r = 1; while (e) { if (e & 1) r = (long long)r * a % MOD; a = (long long)a * a % MOD; e >>= 1; } return r; } // Affine 2 x 3 matrix: // [ a b c ] // [ d e f ] struct Mat { int a, b, c, d, e, f; }; static const Mat ID{1, 0, 0, 0, 1, 0}; inline Mat compose(const Mat &A, const Mat &B) { Mat C; C.a = (1ULL * A.a * B.a + 1ULL * A.b * B.d) % MOD; C.b = (1ULL * A.a * B.b + 1ULL * A.b * B.e) % MOD; C.c = (1ULL * A.a * B.c + 1ULL * A.b * B.f + A.c) % MOD; C.d = (1ULL * A.d * B.a + 1ULL * A.e * B.d) % MOD; C.e = (1ULL * A.d * B.b + 1ULL * A.e * B.e) % MOD; C.f = (1ULL * A.d * B.c + 1ULL * A.e * B.f + A.f) % MOD; return C; } // A state whose two components are affine functions of one variable h: // component 0 = c0 * h + d0 // component 1 = c1 * h + d1 struct AffState { int c0, d0, c1, d1; }; inline void applyMatrix(const Mat &M, AffState &S) { int nc0 = (1ULL * M.a * S.c0 + 1ULL * M.b * S.c1) % MOD; int nd0 = (1ULL * M.a * S.d0 + 1ULL * M.b * S.d1 + M.c) % MOD; int nc1 = (1ULL * M.d * S.c0 + 1ULL * M.e * S.c1) % MOD; int nd1 = (1ULL * M.d * S.d0 + 1ULL * M.e * S.d1 + M.f) % MOD; S = {nc0, nd0, nc1, nd1}; } struct QueryData { int type = 0; // 0: direct answer, 1: matrix calculation int direct = 0; int lca = 0; int B = 0; int alpha = 1, beta = 0; AffState state{0, 0, 0, 0}; }; int main() { FastScanner fs; int N, Q; if (!fs.readInt(N)) return 0; fs.readInt(Q); vector<int> parent(N + 1), depth(N + 1), childCount(N + 1); for (int u = 2; u <= N; ++u) { fs.readInt(parent[u]); depth[u] = depth[parent[u]] + 1; ++childCount[parent[u]]; } vector<int> queryX(Q), queryY(Q); for (int i = 0; i < Q; ++i) { fs.readInt(queryX[i]); fs.readInt(queryY[i]); } vector<int> inv(N + 2); inv[1] = 1; for (int i = 2; i <= N + 1; ++i) { inv[i] = MOD - (long long)(MOD / i) * inv[MOD % i] % MOD; } // E[u]: expected time to leave u's subtree, starting at u. // sumE[u]: sum of E[c] over all children c of u. vector<int> E(N + 1), sumE(N + 1); for (int u = N; u >= 1; --u) { int d = childCount[u]; if (u == 1) { E[u] = 0; // The root has no proper ancestor. } else if (d == 0) { E[u] = 1; } else { int avg = (1 + 1LL * sumE[u] * inv[d]) % MOD; E[u] = 1LL * (depth[u] + 1) * inv[depth[u]] % MOD * avg % MOD; } if (parent[u]) { sumE[parent[u]] = addmod(sumE[parent[u]], E[u]); } } // R[u] = sum of E[v] / (depth[v] + 1) over non-root ancestors v of u. // A[u] = E[u] + R[parent[u]]. vector<int> R(N + 1), A(N + 1); for (int u = 2; u <= N; ++u) { int w = 1LL * E[u] * inv[depth[u] + 1] % MOD; R[u] = addmod(R[parent[u]], w); A[u] = addmod(E[u], R[parent[u]]); } int LOG = 1; while ((1 << LOG) <= N) ++LOG; vector<vector<int>> up(LOG, vector<int>(N + 1)); vector<vector<Mat>> prod(LOG, vector<Mat>(N + 1)); up[0] = parent; for (int j = 0; j < LOG; ++j) prod[j][0] = ID; // Edge matrix for parent[u] -> u. // The root edge is excluded from the recurrence, so it gets identity. prod[0][1] = ID; for (int u = 2; u <= N; ++u) { int p = parent[u]; if (p == 1) { prod[0][u] = ID; continue; } int d = childCount[p]; int delta = depth[p]; int side = submod(sumE[p], E[u]); int r = (1LL * ((1LL * d * delta + 1) % MOD) * inv[delta + 1]) % MOD; int s = (MOD - 1LL * (d - 1) * inv[delta + 1] % MOD) % MOD; int t = (MOD - addmod(d, side)) % MOD; prod[0][u] = {r, s, t, 1, 1, 0}; } // Binary lifting with ordered products of affine edge matrices. for (int j = 1; j < LOG; ++j) { for (int u = 1; u <= N; ++u) { int mid = up[j - 1][u]; up[j][u] = up[j - 1][mid]; prod[j][u] = compose(prod[j - 1][mid], prod[j - 1][u]); } } auto jump = [&](int u, int k) { for (int j = 0; k; ++j, k >>= 1) { if (k & 1) u = up[j][u]; } return u; }; auto lca = [&](int u, int v) { if (depth[u] < depth[v]) swap(u, v); u = jump(u, depth[u] - depth[v]); if (u == v) return u; for (int j = LOG - 1; j >= 0; --j) { if (up[j][u] != up[j][v]) { u = up[j][u]; v = up[j][v]; } } return parent[u]; }; // Collect the binary-lifting blocks of the path top -> bottom. // The returned blocks are in bottom-to-top order. auto collectBlocks = [&](int top, int bottom, const Mat *blocks[]) { int dist = depth[bottom] - depth[top]; int mask = dist; int cur = bottom; int cnt = 0; for (int j = 0; mask; ++j, mask >>= 1) { if (mask & 1) { blocks[cnt++] = &prod[j][cur]; cur = up[j][cur]; } } return cnt; }; // Apply all edge matrices on top -> bottom to an affine state. auto applyPath = [&](int top, int bottom, int B0) { AffState S{1, 0, 1, B0}; const Mat *blocks[32]; int cnt = collectBlocks(top, bottom, blocks); for (int i = cnt - 1; i >= 0; --i) { applyMatrix(*blocks[i], S); } return S; }; vector<QueryData> data(Q); for (int i = 0; i < Q; ++i) { int x = queryX[i]; int y = queryY[i]; if (x == y) { data[i].type = 0; data[i].direct = 0; continue; } if (y == 1) { data[i].type = 0; data[i].direct = A[x]; continue; } int l = lca(x, y); int v1 = jump(y, depth[y] - 1); int side = submod(sumE[1], E[v1]); int B0 = addmod(childCount[1], side); AffState full = applyPath(v1, y, B0); data[i].type = 1; data[i].lca = l; data[i].B = B0; data[i].alpha = full.c0; data[i].beta = full.d0; if (l == 1) { // H_1 = Q_0 = h + B0, and Q_{-1} = 0. data[i].state = {1, B0, 0, 0}; } else if (l == y) { // H_y = 0; the second component is Q_{y-1}. data[i].state = {0, 0, full.c1, full.d1}; } else { data[i].state = applyPath(v1, l, B0); } } // Batch inversion of all alpha values. vector<int> pref(Q + 1, 1), invAlpha(Q, 1); for (int i = 0; i < Q; ++i) { pref[i + 1] = pref[i]; if (data[i].type == 1) { pref[i + 1] = 1LL * pref[i] * data[i].alpha % MOD; } } int curInv = modPow(pref[Q], MOD - 2); for (int i = Q - 1; i >= 0; --i) { if (data[i].type == 1) { invAlpha[i] = 1LL * curInv * pref[i] % MOD; curInv = 1LL * curInv * data[i].alpha % MOD; } } string output; output.reserve((size_t)Q * 12); for (int i = 0; i < Q; ++i) { int ans; if (data[i].type == 0) { ans = data[i].direct; } else { int h = (MOD - data[i].beta) % MOD; h = 1LL * h * invAlpha[i] % MOD; int hL = (1LL * data[i].state.c0 * h + data[i].state.d0) % MOD; int qPrev = (1LL * data[i].state.c1 * h + data[i].state.d1) % MOD; int l = data[i].lca; int x = queryX[i]; if (l == x) { ans = hL; } else { int sum = addmod(hL, qPrev); int tail = 1LL * sum * inv[depth[l] + 1] % MOD; ans = addmod(submod(A[x], R[l]), tail); } } output += to_string(ans); output.push_back('\n'); } fwrite(output.data(), 1, output.size(), stdout); return 0; }
#include <bits/stdc++.h> using namespace std; static constexpr int MOD = 1'000'000'007; inline int addmod(int a, int b) { int s = a + b; if (s >= MOD) s -= MOD; return s; } inline int submod(int a, int b) { int s = a - b; if (s < 0) s += MOD; return s; } inline int mulmod(int a, int b) { return int(1LL * a * b % MOD); } inline int normalize(long long x) { x %= MOD; if (x < 0) x += MOD; return int(x); } int modpow(int a, int e) { int result = 1; while (e > 0) { if (e & 1) result = mulmod(result, a); a = mulmod(a, a); e >>= 1; } return result; } struct FastScanner { static constexpr int SIZE = 1 << 16; char buffer[SIZE]; int pos = 0, len = 0; inline int getChar() { if (pos == len) { len = int(fread(buffer, 1, SIZE, stdin)); pos = 0; if (len == 0) return EOF; } return buffer[pos++]; } int nextInt() { int c; do { c = getChar(); } while (c <= ' ' && c != EOF); int x = 0; while (c >= '0' && c <= '9') { x = x * 10 + (c - '0'); c = getChar(); } return x; } }; // Affine transformation: // [a b; c d] * z + [e; f] struct Affine { int a, b, c, d, e, f; }; int main() { FastScanner fs; int N = fs.nextInt(); int Q = fs.nextInt(); vector<int> parent(N + 1, 1); vector<int> depth(N + 1, 0); vector<int> childCount(N + 1, 0); vector<int> head(N + 1, 0); vector<int> nxt(N + 1, 0); for (int v = 2; v <= N; ++v) { int p = fs.nextInt(); parent[v] = p; depth[v] = depth[p] + 1; ++childCount[p]; nxt[v] = head[p]; head[p] = v; } vector<int> invNum(N + 2); invNum[1] = 1; for (int i = 2; i <= N + 1; ++i) { invNum[i] = MOD - int(1LL * (MOD / i) * invNum[MOD % i] % MOD); } /* For a target-free subtree rooted at v: S_v = alpha[v] * S_parent(v) + beta[v]. */ vector<int> alpha(N + 1, 0); vector<int> beta(N + 1, 0); vector<int> invAlpha(N + 1, 0); // D[v] = 2 * childCount[v] - sum alpha[child] // C[v] = childCount[v] + sum beta[child] vector<int> D(N + 1, 0); vector<int> C(N + 1, 0); for (int v = N; v >= 2; --v) { if (childCount[v] == 0) { int d = depth[v]; alpha[v] = mulmod(d + 1, invNum[d]); beta[v] = 1; invAlpha[v] = mulmod(d, invNum[d + 1]); } else { int sumAlpha = 0; int sumBeta = 0; for (int c = head[v]; c != 0; c = nxt[c]) { sumAlpha = addmod(sumAlpha, alpha[c]); sumBeta = addmod(sumBeta, beta[c]); } D[v] = submod(2 * childCount[v], sumAlpha); C[v] = addmod(childCount[v], sumBeta); int invD = (D[v] == 1 ? 1 : modpow(D[v], MOD - 2)); alpha[v] = mulmod(childCount[v], invD); beta[v] = mulmod(C[v], invD); invAlpha[v] = mulmod(invD, invNum[childCount[v]]); } } { int sumAlpha = 0; int sumBeta = 0; for (int c = head[1]; c != 0; c = nxt[c]) { sumAlpha = addmod(sumAlpha, alpha[c]); sumBeta = addmod(sumBeta, beta[c]); } D[1] = submod(2 * childCount[1], sumAlpha); C[1] = addmod(childCount[1], sumBeta); } alpha[1] = 1; beta[1] = 0; invAlpha[1] = 1; /* pathMat[v] is the affine transformation from V_parent(v) to V_v, where V_v = [S_v; S_parent(v)]. */ vector<Affine> pathMat(N + 1); pathMat[1] = {1, 0, 0, 1, 0, 0}; for (int v = 2; v <= N; ++v) { int p = parent[v]; int edgeD = addmod(D[p], alpha[v]); int edgeK = submod(C[p], beta[v]); int k = childCount[p]; const Affine &P = pathMat[p]; Affine &Q = pathMat[v]; Q.a = normalize(1LL * edgeD * P.a - 1LL * k * P.c); Q.b = normalize(1LL * edgeD * P.b - 1LL * k * P.d); Q.c = P.a; Q.d = P.b; Q.e = normalize(1LL * edgeD * P.e - 1LL * k * P.f - edgeK); Q.f = P.e; } /* Formal upward composition using the standard subtree relations. Q_v(S_v) = qa[v] * S_v + qb[v]. */ vector<int> qa(N + 1, 0); vector<int> qb(N + 1, 0); vector<int> invQa(N + 1, 0); vector<int> upConstant(N + 1, 0); qa[1] = 1; qb[1] = 0; invQa[1] = 1; for (int v = 2; v <= N; ++v) { int p = parent[v]; upConstant[v] = submod(0, mulmod(beta[v], invAlpha[v])); qa[v] = mulmod(qa[p], invAlpha[v]); qb[v] = addmod(mulmod(qa[p], upConstant[v]), qb[p]); invQa[v] = mulmod(invQa[p], alpha[v]); } /* For target y, rootValue[y] is S_root in the corresponding hitting-time solution. */ vector<int> denominator(N + 1, 1); vector<int> prefixProduct(N + 1, 1); vector<int> invDenominator(N + 1, 1); vector<int> rootValue(N + 1, 0); for (int v = 2; v <= N; ++v) { denominator[v] = submod(pathMat[v].a, pathMat[v].c); prefixProduct[v] = mulmod(prefixProduct[v - 1], denominator[v]); } int inverseProduct = modpow(prefixProduct[N], MOD - 2); for (int v = N; v >= 2; --v) { invDenominator[v] = mulmod(inverseProduct, prefixProduct[v - 1]); inverseProduct = mulmod(inverseProduct, denominator[v]); int numerator = submod(pathMat[v].f, pathMat[v].e); rootValue[v] = mulmod(numerator, invDenominator[v]); } // Binary lifting for LCA. int LOG = 1; while ((1 << LOG) <= N) ++LOG; vector<vector<int>> up(LOG, vector<int>(N + 1)); up[0][1] = 1; for (int v = 2; v <= N; ++v) up[0][v] = parent[v]; for (int j = 1; j < LOG; ++j) { for (int v = 1; v <= N; ++v) { up[j][v] = up[j - 1][up[j - 1][v]]; } } auto lca = [&](int u, int v) -> int { if (depth[u] < depth[v]) swap(u, v); int difference = depth[u] - depth[v]; for (int j = 0; j < LOG; ++j) { if ((difference >> j) & 1) u = up[j][u]; } if (u == v) return u; for (int j = LOG - 1; j >= 0; --j) { if (up[j][u] != up[j][v]) { u = up[j][u]; v = up[j][v]; } } return parent[u]; }; string output; output.reserve(size_t(Q) * 12); while (Q--) { int x = fs.nextInt(); int y = fs.nextInt(); if (x == y) { output += "0\n"; continue; } int l = lca(x, y); // V_l = pathMat[l] * [S_root; 0] + constant. int Sl = addmod(mulmod(pathMat[l].a, rootValue[y]), pathMat[l].e); int SparentL = addmod(mulmod(pathMat[l].c, rootValue[y]), pathMat[l].f); int answer; if (l == x) { answer = submod(Sl, SparentL); } else { // Cancel the common formal prefix above l. int value = addmod(mulmod(qa[l], Sl), qb[l]); value = submod(value, qb[x]); int Sx = mulmod(invQa[x], value); int SparentX = addmod(mulmod(invAlpha[x], Sx), upConstant[x]); answer = submod(Sx, SparentX); } output += to_string(answer); output.push_back('\n'); } fwrite(output.data(), 1, output.size(), stdout); return 0; }