Under construction

Still being built. Things may change

Flight

Time limit1sMemory limit256 MB

Summary
Given a tree and queries (u, v, d), find the fewest steps from u to v when each step must join two vertices at distance at least d, or -1 if unreachable.
Level

Hard8 of 10

Topics
Tree, Shortest path, Greedy
Solved
No attempts yet

Problem

You are given a tree with NN vertices. The distance between two vertices is the number of edges on the simple path between them.

There are QQ queries. Each query gives two vertices uu and vv and an integer dd. A pair of vertices is called good if the distance between them is at least dd. In each step, you can only move between a good pair of vertices. Find the minimum number of steps needed to get from uu to vv. If the destination cannot be reached, the answer is −1-1.

The queries are generated from a formula, so there are many of them.

Input

The first line contains three integers NN, QQ, and MM: the number of vertices, the number of queries, and the upper bound for dd. (1≤N≤2⋅1051 \leq N \leq 2 \cdot 10^5, 1≤Q≤1061 \leq Q \leq 10^6, 1≤M≤2⋅1051 \leq M \leq 2 \cdot 10^5).

The second line contains N−1N - 1 integers f2f_2, f3f_3, …\ldots, fNf_N. For every ii with 2≤i≤N2 \leq i \leq N, there is an edge between vertices ii and fif_i (1≤fi<i1 \leq f_i < i).

The third line contains six integers u1u_1, v1v_1, d1d_1, AA, BB, and CC (1≤u1,v1≤N1 \leq u_1, v_1 \leq N, 0≤d1<M0 \leq d_1 < M, 104≤A,B,C≤2⋅10410^4 \leq A, B, C \leq 2 \cdot 10^4). The first query is given by u1u_1, v1v_1, and d1d_1.

For 2≤i≤Q2 \leq i \leq Q, the ii-th query is generated as follows:

ui=((A⋅ui−1+B+ansi−1) mod N)+1u_i = ((A \cdot u_{i-1} + B + \mathit{ans}_{i-1}) \bmod N) + 1,

vi=((B⋅vi−1+C+ansi−1) mod N)+1v_i = ((B \cdot v_{i-1} + C + \mathit{ans}_{i-1}) \bmod N) + 1,

di=(C⋅di−1+A+ansi−1) mod Md_i = (C \cdot d_{i-1} + A + \mathit{ans}_{i-1}) \bmod M.

Here, ansk\mathit{ans}_k is the answer to query kk.

Output

Output the integer

S=∑i=1Qi⋅(ansi+1)S = \sum_{i=1}^{Q} i \cdot (\mathit{ans}_i + 1)

Examples1

  1. Example 1

    Input
    6 9 5
    1 2 1 3 3
    6 3 0 10865 16947 15183
    
    Expected output
    55