#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
vector<pair<long long, long long> > adj[maxn];
map<long long, long long> cnt[maxn], cd[maxn];
long long sz[maxn], h[maxn];
long long up[maxn], dw[maxn], inv[maxn], pw[maxn];
long long ans = 0, M;
bool mark[maxn];
pair<long long, long long> bezo(long long a, long long b) {
  if (a == (long long)1) return (make_pair(1, 0));
  auto x = bezo(b % a, a);
  return (make_pair(x.second - b / a * x.first, x.first));
}
long long inverse(long long a, long long b) {
  return ((bezo(a, b).first + b) % b);
}
void dfs(int u, int p = -1) {
  sz[u] = 1;
  for (auto v : adj[u]) {
    if (!mark[v.first] && v.first != p) {
      dfs(v.first, u);
      sz[u] += sz[v.first];
    }
  }
}
int find_centroid(int u, int v, int p = -1) {
  for (auto x : adj[v]) {
    if (!mark[x.first] && x.first != p && sz[x.first] > sz[u] / 2) {
      return find_centroid(u, x.first, v);
    }
  }
  return v;
}
void dfs2(int v, int p, int pt) {
  cnt[0][up[v]]++;
  cd[0][dw[v]]++;
  cnt[pt][up[v]]++;
  cd[pt][dw[v]]++;
  for (auto u : adj[v]) {
    if (!mark[u.first] && u.first != p) {
      h[u.first] = h[v] + 1;
      up[u.first] = (up[v] + pw[h[v]] * u.second % M) % M;
      dw[u.first] = (1LL * dw[v] * 10 + u.second % M) % M;
      dfs2(u.first, v, pt);
    }
  }
}
void dfs3(int v, int p, int pt) {
  long long val = ((-1LL * dw[v] * inv[h[v]] % M) + M) % M;
  ans += cnt[0][val] - cnt[pt][val];
  for (auto u : adj[v]) {
    if (!mark[u.first] && u.first != p) {
      dfs3(u.first, v, pt);
    }
  }
}
void solve(int v) {
  dfs(v);
  int c = find_centroid(v, v);
  mark[c] = true;
  up[c] = dw[c] = 0;
  h[c] = 0;
  for (int i = 0; i < adj[c].size(); i++) {
    int u = adj[c][i].first;
    int w = adj[c][i].second;
    if (!mark[u]) {
      h[u] = 1;
      up[u] = dw[u] = w % M;
      dfs2(u, c, i + 1);
    }
  }
  for (int i = 0; i < adj[c].size(); i++) {
    int u = adj[c][i].first;
    if (!mark[u]) {
      ans += cnt[i + 1][0] + cd[i + 1][0];
      dfs3(u, c, i + 1);
    }
  }
  for (int i = 0; i <= adj[c].size() + 2; i++) {
    cnt[i].clear();
    cd[i].clear();
  }
  for (auto u : adj[c]) {
    if (!mark[u.first]) {
      solve(u.first);
    }
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ;
  int n;
  cin >> n >> M;
  for (int i = 0; i < n - 1; i++) {
    int x, y, w;
    cin >> x >> y >> w;
    adj[x].push_back({y, w});
    adj[y].push_back({x, w});
  }
  if (M == 1) {
    cout << 1LL * n * (n - 1) << endl;
    return 0;
  }
  pw[0] = 1;
  for (int i = 1; i <= n; i++) {
    pw[i] = 1LL * pw[i - 1] * 10 % M;
    inv[i] = inverse(pw[i], M);
  }
  solve(0);
  cout << ans;
  return 0;
}
