问题 D: Distance on Tree

内存限制:512 MB 时间限制:1 S 标准输入输出
题目类型:传统 评测方式:Special Judge 上传者:
提交:1 通过:1

题目描述

链接:https://ac.nowcoder.com/acm/contest/57362/D
来源:牛客网
You are given a rooted tree with nnn nodes labeled from 111 to nnn, the root of which is the 111-st node, and the iii-th node has a given value aia_iai for each i=1,2,…,ni = 1, 2, \ldots, ni=1,2,,n.

Given a parameter mmm and then qqq queries, the iii-th of which is represented by two numbers xix_ixi and kik_iki, your task is to maximize dis(u,v)+dis(v,w)+dis(w,u)dis(u,v)+dis(v,w)+dis(w,u)dis(u,v)+dis(v,w)+dis(w,u) by choosing three distinct nodes uuu, vvv and www in the subtree of xix_ixi such that au+av+aw≡ki(modm)a_u+a_v+a_w \equiv k_i \pmod mau+av+awki(modm). Here dis(u,v)dis(u,v)dis(u,v) is the length of the shortest path between the uuu-th and the vvv-th nodes on the tree. If there is no solution for a query, the answer is 000.

输入格式

The first line contains three integers n,mn,mn,m (1≤n,m≤20001 \le n, m \le 2\,0001n,m2000) and qqq (1≤q≤2×1051 \le q \le 2 \times 10^51q2×105).
The second line contain nnn integers a1,a2,…,ana_1, a_2, \ldots, a_na1,a2,,an (0≤ai<m0 \le a_i < m0ai<m).
Following n−1n - 1n1 lines describe the tree, each of which contains three integers u,vu, vu,v (1≤u,v≤n1 \le u, v \le n1u,vn) and www (1≤w≤2×1051 \le w \le 2 \times 10^51w2×105), representing an edge with length www between the uuu-th and the vvv-th nodes.
In the following qqq lines, the iii-th line contains two integers xix_ixi (1≤xi≤n1 \le x_i \le n1xin) and kik_iki (0≤ki<m0 \le k_i < m0ki<m), describing the iii-th query.

输出格式

Output qqq lines, the iii-th of which contains an integer, indicating the answer to the iii-th query.

输入样例 复制

5 5 10
0 1 2 3 4
1 2 1
2 3 2
2 4 3
1 5 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
2 4

输出样例 复制

12
14
16
16
20
0
10
0
0
0