#include <bits/stdc++.h>
using namespace std;
int father[100005];
long long size[100005];
const int mod = 1000000007;
int find(int x) {
  if (father[x] == x) return x;
  return father[x] = find(father[x]);
}
int main() {
  for (int i = 0; i < 100005; i++) {
    father[i] = i;
    size[i] = 1;
  }
  int n, k;
  cin >> n >> k;
  for (int i = 0; i < n - 1; i++) {
    int tmp, tmp1, tmp2;
    cin >> tmp >> tmp1 >> tmp2;
    if (tmp2 == 0) {
      int u = find(tmp);
      int v = find(tmp1);
      father[u] = v;
      size[v] += size[u];
    }
  }
  long long sum = 0;
  for (int i = 1; i <= n; i++) {
    if (father[i] == i) {
      long long tmp = size[i];
      for (int j = 1; j < k; j++) {
        size[i] *= tmp;
        size[i] %= mod;
      }
      sum += size[i] % mod;
    }
  }
  long long nk = 1;
  for (int i = 0; i < k; i++) {
    nk *= n;
    nk %= mod;
  }
  cout << ((nk - sum) % mod + mod) % mod;
  return 0;
}
