#P4427. [BJOI2018] 求和

    ID: 3365 远端评测题 2000ms 500MiB 尝试: 0 已通过: 0 难度: 6 上传者: 标签>2018倍增各省省选北京O2优化深度优先搜索,DFS最近公共祖先,LCA树链剖分,树剖前缀和

[BJOI2018] 求和

Description

master is very interested in sums on trees. He generated a rooted tree and wants to query, multiple times, the sum of the kk-th power of the depths of all nodes on a path, and kk may be different each time. Here, the depth of a node is defined as the number of edges on the path from this node to the root. He handed this problem to pupil, but pupil does not know how to perform such complex operations. Can you help him?

Input Format

The first line contains a positive integer nn, the number of nodes in the tree.

Each of the next n1n - 1 lines contains two space-separated positive integers i,ji, j, indicating an edge between nodes ii and jj in the tree.

The next line contains a positive integer mm, the number of queries.

Each of the next mm lines contains three space-separated positive integers i,j,ki, j, k, representing a query asking for the sum of the kk-th power of the depths of all nodes on the path from node ii to node jj. Since the result can be very large, output it modulo 998244353998244353.

Nodes are numbered starting from 11, and node 11 is the root.

Output Format

For each query, output one line with a single integer, the result modulo 998244353998244353.

5
1 2
1 3
2 4
2 5
2
1 4 5
5 4 45
33
503245989

Hint

Sample Explanation

Let d(i)d (i) denote the depth of node ii.

For the sample tree, $d (1) = 0, d (2) = 1, d (3) = 1, d (4) = 2, d (5) = 2$.

Therefore, the answer to the first query is (25+15+05)mod998244353=33(2^5 + 1^5 + 0^5) \bmod 998244353 = 33; the answer to the second query is $(2^{45} + 1^{45} + 2^{45}) \bmod 998244353 = 503245989$.

Constraints

  • For 30%30\% of the testdata, 1n,m1001 \leq n, m \leq 100.
  • For 60%60\% of the testdata, 1n,m10001 \leq n, m \leq 1000.
  • For 100%100\% of the testdata, 1n,m3000001 \leq n, m \leq 300000, 1k501 \leq k \leq 50.

Additionally, there are 55 unscored hack testdata.

Tip

The input size is large; please use fast I/O.

Translated by ChatGPT 5