#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
int f[100005];
long long cnt[100005];
long long ans;
long long find(int x) {
  if (f[x] == x) return x;
  f[x] = find(f[x]);
  return f[x];
}
void merge(int x, int y) {
  int fx = find(x);
  int fy = find(y);
  if (fx != fy) {
    f[fy] = fx;
  }
}
long long ksm(long long a, long long n) {
  long long ans = 1;
  while (n) {
    if (n & 1) ans = ans * a % mod;
    a = a * a % mod;
    n = n >> 1;
  }
  return ans;
}
int main() {
  int n, k;
  cin >> n >> k;
  for (int i = 1; i <= n; i++) {
    f[i] = i;
  }
  int x, y, w;
  for (int i = 1; i <= n - 1; i++) {
    cin >> x >> y >> w;
    if (w == 0) {
      merge(x, y);
      cnt[x] += cnt[y];
    }
  }
  for (int i = 1; i <= n; i++) cnt[find(i)]++;
  for (int i = 1; i <= n; i++) {
    if (f[i] == i) {
      ans = (ans % mod + ksm(cnt[i], k) % mod) % mod;
    }
  }
  cout << (ksm(n, k) + mod - ans) % mod;
  return 0;
}
