#include <bits/stdc++.h>
const int N = 1e5 + 2, p = 1e9 + 7;
int siz[N], f[N];
int n, m, x, y, z, i, c;
inline void read(int &x) {
  c = getchar();
  while ((c < 48) || (c > 57)) c = getchar();
  x = c ^ 48;
  c = getchar();
  while ((c >= 48) && (c <= 57)) {
    x = x * 10 + (c ^ 48);
    c = getchar();
  }
}
int getf(register int x) {
  if (f[x] == x) return f[x];
  f[x] = getf(f[x]);
  siz[f[x]] += siz[x];
  siz[x] = 0;
  return f[x];
}
inline int ksm(register int x, register int y) {
  register int r = 1;
  while (y) {
    if (y & 1) r = (long long)r * x % p;
    x = (long long)x * x % p;
    y >>= 1;
  }
  return r;
}
int main() {
  read(n);
  read(m);
  for (i = 1; i <= n; i++) siz[f[i] = i] = 1;
  for (i = 1; i < n; i++) {
    read(x);
    read(y);
    read(z);
    if (z == 0) {
      siz[getf(y)] += siz[getf(x)];
      siz[f[x]] = 0;
      f[f[x]] = f[y];
    }
  }
  c = ksm(n, m);
  for (i = 1; i <= n; i++)
    if (siz[i]) c = (c - ksm(siz[i], m) + p) % p;
  printf("%d", c);
}
