TreePath Divisibility

4.7

3 votes
Algorithms, Graphs, Euler Tour and Path
Problem

You are tasked with solving a problem involving a tree structure consisting of N nodes and N1 edges. Each node in the tree is associated with a distinct value A[i]. That means all the values of the nodes are distinct.

Your objective is to process Q queries, where each query provides three integers: X, Y, and K. Your goal is to determine the count of  nodes along the simple path from node X to node Y (inclusive) such that the values of the nodes are divisible by K.

Input format

  • First line of the input contains an integer T, representing the number of test cases.
  • The first line of each test case contains 2 space-separated integers NQ representing the number of nodes and the number of queries respectively.
  • The next line of each test case contains N integers seperated by a space representing the array A.
  • Next N1 lines of each test case contains 2 space-separated integers a,b, representing that there's an edge between node a and node b.
  • The next Q lines of each test case contains 3 space-separated integers X,Y,K representing the queries.

Output format

For each query output the answer in a new line representing the count of nodes divisible by K, on a path from Node X to Node Y inclusive.

Constraints

  • 1T105
  • 2N,Q105
  • 1A[i]N
  • 1a,b,X,Y,KN,ab,XY
  • It is guaranteed that the sum of N, Q over all test cases does not exceed 2105

 

Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

 For test case 1:

  • In the first query all 5 values on the path from node 1 to node 5 are divisible by 1, hence the answer is 5.
  • In second and fourth query values of only 2nd and 4th nodes on the path are divisible by 2, hence the answer is 2.
  • In the fifth query the value of only 4th node on the path is divisible by 4, hence the answer is 1.
Editor Image

?