跳到主要内容
图灵 OJTURING / ONLINE JUDGE

#F1093. Digit Tree

    ID: 1099 传统题 2000ms 256MiB 尝试: 0 已通过: 0 难度: 9 上传者: 标签>搜索分治并查集算法思想数据结构挑战难度共享题库Codeforces英文题面题目来源题面语言

Digit Tree

题目描述

C. Digit Tree
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

ZS the Coder has a large tree. It can be represented as an undirected connected graph of n vertices numbered from 0 to n-1 and n-1 edges between them. There is a single nonzero digit written on each edge.

One day, ZS the Coder was bored and decided to investigate some properties of the tree. He chose a positive integer M, which is coprime to 10, i.e. .

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 a1=u,a2,...,ak=v be the sequence of vertices on the shortest path from u to v in the order of encountering them;
  • Let di (1≤i<k) be the digit written on the edge between vertices ai and ai+1;
  • The integer is divisible by M.

Help ZS the Coder find the number of interesting pairs!

Input

The first line of the input contains two integers, n and M (2≤n≤100000,1≤M≤109, )− 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 ui,vi and wi, denoting an edge between vertices ui and vi with digit wi written on it (0≤ui,vi<n,1≤wi≤9).

Output

Print a single integer− the number of interesting (by ZS the Coder's consideration) pairs.

Examples
Input
6 7
0 1 2
4 2 4
2 0 1
3 0 9
2 5 7
Output
7
Input
5 11
1 2 3
2 0 3
3 0 3
4 3 3
Output
8
Note

In the first sample case, 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.

In the second sample case, 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.


题目来源:fps-www.educg.net-codeforce-1-2833.xml.zip;FPS 共享题包,题包内第 556 题。保留原作者与原赛事署名。