2006: CF715 - C. Digit Tree
Description
ZS consider an ordered pair of distinct vertices $(u,v)$ interesting when if he would follow the shortest path from vertex $u$ to vertex $v$ and write down all the digits he encounters on his path in the same order, he will get a decimal representaion of an integer divisible by $M$.
Formally, ZS consider an ordered pair of distinct vertices $(u,v)$ interesting if the following states true:
- Let $a_1=u,a_2,...,a_k=v$ be the sequence of vertices on the shortest path from $u$ to $v$ in the order of encountering them;
- Let $d_i\ (1≤i<k)$ be the digit written on the edge between vertices $a_i$ and $a_{i+1}$;
- The integer $\overline{d_1d_2\cdots d_{k-1}}=\sum_{i=1}^{k-1} d_i \times 10^{k-1-i}$ is divisible by $M$.
Input
The first line of the input contains two integers, $n,M\ (2≤n≤100000,\ 1≤M≤10^9,\ \text{gcd}(M,10)=1)$ − the number of vertices and the number ZS has chosen respectively.
The next $n-1$ lines contain three integers each. $i$-th of them contains $u_i,v_i,w_i$, denoting an edge between vertices $u_i$ and $v_i$ with digit $w_i$ written on it $(0≤u_i,v_i<n,\ 1≤w_i≤9)$.
Output
Sample 1 Input
6 7
0 1 2
4 2 4
2 0 1
3 0 9
2 5 7
Sample 1 Output
7
the interesting pairs are (0,4),(1,2),(1,5),(3,2),(2,5),(5,2),(3,5). The numbers that are formed by these pairs are 14,21,217,91,7,7,917 respectively, which are all multiples of 7. Note that (2,5) and (5,2) are considered different.
Sample 2 Input
5 11
1 2 3
2 0 3
3 0 3
4 3 3
Sample 2 Output
8
the interesting pairs are (4,0),(0,4),(3,2),(2,3),(0,1),(1,0),(4,1),(1,4), and 6 of these pairs give the number 33 while 2 of them give the number 3333, which are all multiples of 11.