Little Shino and Path Divisor

4

10 votes
Approved, Data Structures, Disjoint set, Medium
Problem

There is no partial marking in the problem.

Given a weighted undirected tree of N nodes and Q queries. Each query contains an integer D. For each query, find the number of paths in the given tree such that all the edges in the path are divisible by D.

Input Format:
First line contains two space separated integers, N and Q (1N,Q105), denoting number of nodes in the tree and number of queries. Next N1 line contains three space separated integers, X, Y and W (1X,YN) (1W105), denoting that there is an edge between X and Y of weight W. Next Q lines contains one integer each, D (1D105).

Output Format:
For each query, print number of paths such that all the edges in the path are divisible by D in new line.

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

enter image description here

First query, D=5 :
There are 4 paths such that all the edges in the path are divisible by D.
1. 1 -> 2
2. 3 -> 4
3. 3 -> 5
4. 4 -> 3 -> 5

Second query, D=3 :
There are 6 paths such that all the edges in the path are divisible by D.
1. 1 -> 3
2. 3 -> 4
3. 3 -> 5
4. 4 -> 3 -> 5
5. 1 -> 3 -> 5
6. 1 -> 3 -> 4

Editor Image

?