Beautiful Pairs

3.8

4 votes
Algorithms, Hard, Square Root Decomposition
Problem

You live in a city that consists of N restaurants. Each restaurant has a unique index between 1 and N (both inclusive) and value denoted by the array V . A unique path exists between every pair of restaurants, which implies that each restaurant can be reached from every other restaurant. You are given an integer P. Your task is to solve Q queries of the following form:  

A B L1 R1 L2 R2

where A and B are the indices of two distinct restaurants and L1, R1, L2, and R2 are positive integers. For each query, determine the total number of ordered pairs of restaurants (X,Y) such that the following conditions hold:

  • X lies in the unique path between the restaurants A and B

  • A lies in the unique path between the restaurants X and Y

  • L1(VX%P)R1

  • L2(VY%P)R2

  • A, B, X, and Y should be pairwise distinct

Input format

  • First line: Three space-separated integers N , Q, and P 
  • Second line: N space-separated integers with ith integer denoting Vi 
  • Next N1 lines: Two space-separated integers U and V denoting a bidirectional path from restaurant U to V and vice versa
  • Next Q lines: Six space-separated integers IN1, IN2, IN3, IN4, IN5, and IN6describing one query. Let last denote the answer of the previous query (if its first query then last = 0). The parameters of the query can be calculated by the following conditions: 
    • A=IN1last
    • B=IN2last
    • L1=IN3last
    • R1=IN4last
    • L2=IN5last
    • R2=IN6last

where  is the symbol for the bitwise XOR.

Output format

For each query, print the answer on a separate line.

Constraints

2N,Q105

1A,BN and AB

1L1,R1,L2,R2,P,Vi109

L1R1 and L2R2

Subtasks

  • For 10 points: 2N,Q100
  • For 20 points: 2N,Q5000
  • For 70 points: Original Constraints
Sample Input
11 5 20
10 5 6 10 10 10 10 10 10 10 10 
1 2
1 3
2 4
2 5
4 6
4 7
5 8
3 9
9 10
9 11
4 9 1 20 1 20
2 13 7 18 7 18
12 3 9 1 9 1
4 2 1 10 1 10
4 1 1 10 1 10
Sample Output
6
8
0
0
2
Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

For the first query the possible pairs satisfying all the conditions are (1,6), (2,6), (3,6), (1,7), (2,7) and (3,7).

Editor Image

?