#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1);
const int N = 1e5 + 7, mod = 1000000007, M = 2e9;
const long long MAX = 5e18;
int moding(long long x) {
  while (x < 0) x += mod;
  if (x >= mod) x %= mod;
  return x;
}
int n, k, u, v, x, c[N];
long long ans = 1;
struct dsu {
  int sz[N], cl[N];
  void init() {
    fill(sz, sz + N, 0);
    iota(cl, cl + N, 0);
  }
  int par(int x) { return cl[x] = (x == cl[x] ? x : par(cl[x])); }
  void con(int x, int y) {
    x = par(x);
    y = par(y);
    if (x == y) return;
    if (sz[y] > sz[x]) swap(x, y);
    sz[x] += sz[y];
    cl[y] = x;
  }
} tree;
long long fac(int x) {
  long long ret = 1;
  for (int i = 0; i < k; i++) ret = moding(ret * x);
  return ret;
}
int main() {
  scanf("%d%d", &n, &k);
  tree.init();
  for (int i = 1; i < n; i++) {
    scanf("%d%d%d", &u, &v, &x);
    if (!x) tree.con(u, v);
  }
  for (int i = 1; i <= n; i++) c[tree.par(i)]++;
  ans = fac(n);
  for (int i = 1; i <= n; i++) ans = moding(ans - fac(c[i]));
  cout << ans;
  return 0;
}
