Mind Palace

0

0 votes
Medium-Hard
Problem

"Get Out! I Need To Go To My Mind Palace!" - Sherlock

Problem 8

A tree is a connected graph that doesn't contain any cycles. This tree is a special one with N nodes and each of the N1 edges has some weight associated with it.

Distance between two vertices of the tree is the product of edge weights on the shortest path between the two vertices. Since this product might get too large, we will compute distance modulo MOD.

Given an integer P , you needs to find the number of unordered (u,v) pairs such that distance between u and v modulo MOD is equal to P.

Input:

First line of input contains 2 integer N and MOD, denoting the number of nodes in the tree and the modulo with which we are computing distances. Each of the next N1 lines contains 3 integers X, Y and Z, meaning that there is an edge between node X and node Y of weight Z. Next line contains an integer P.

Output:

Print the answer as described in problem statement. If you count (u,v) in the answer, do not count (v,u).

Constraints:

1N2105

3MOD109+7

MOD is prime.

0PMOD1

1X,YN

1ZMOD1

Note:

This problem has binary scoring. You will get 100 points if you pass all test cases.

Time Limit: 3
Memory Limit: 256
Source Limit:
Editor Image

?