Digital Tree#10163

Digital Tree

3.5 seconds
64 megabytes
Easy

Nazik has a large tree, which can be represented as an undirected connected graph with vertices, numbered from to , and n - 1 edges. Each edge has a nonzero digit written on it.

Max, Nazik's friend, is particularly interested in special paths within this tree. Max's favorite number is , which is coprime with , i.e., \gcd(M, 10) = 1.

Max and Nazik define an ordered pair of different vertices as special if, when traversing the unique path from vertex to vertex , the sequence of digits encountered forms a decimal number divisible by .

Formally, an ordered pair of different vertices is special if:

Your task is to determine the number of special pairs.

Input

The first line contains two integers and (2 \leq n \leq 100\,000, 1 \leq M \leq 10^9, \gcd(M, 10) = 1) — the number of vertices and Max's favorite number.

The next n - 1 lines each contain three integers u_i, v_i, and w_i, indicating an edge between vertices u_i and v_i with the digit w_i (1 \leq u_i, v_i \leq n, 1 \leq w_i \leq 9) written on it.

Output

Output a single integer — the number of special pairs.

Examples

\begin{example}\exmp{6 71 2 11 3 42 4 22 5 33 6 7}{7}%\exmp{5 111 2 32 3 33 4 34 5 3}{8}%\end{example}

Example 1

Loading
Loading

Note

In the first example, the special pairs are , , , , , , .

The numbers formed by these paths are , , , , , , and , respectively, all divisible by . Note that and are considered different pairs.

In the second example, the special pairs are , , , , , , , and . For these, pairs correspond to the number and pairs to the number , all divisible by .