#include <bits/stdc++.h>
using namespace std;
const int inf = -0x3ffffff;
const int maxn = 5e6 + 5;
int fa[maxn];
int fin(int x) {
  if (x == fa[x]) return x;
  return fa[x] = fin(fa[x]);
}
long long n, m;
long long vis[maxn];
const long long mod = 1e9 + 7;
long long get(long long x, long long y) {
  long long ans = 1;
  long long h = x;
  while (y) {
    if (y % 2) ans = ans * x % mod;
    y /= 2;
    x = x * x % mod;
  }
  return (ans - h + mod) % mod;
}
int main() {
  cin >> n >> m;
  for (long long i = 1; i <= n + 5; i++) fa[i] = i;
  for (int i = 0; i < n - 1; i++) {
    long long l, r, t;
    cin >> l >> r >> t;
    if (!t) {
      int x = fin(l), y = fin(r);
      fa[x] = y;
    }
  }
  for (int i = 1; i <= n; i++) {
    vis[fin(i)]++;
  }
  long long ans = 0;
  long long res = get(n, m);
  for (int i = 1; i <= n; i++) {
    if (fin(i) == i) {
      res -= get(vis[i], m);
      res = (res + mod) % mod;
    }
  }
  cout << (res + mod) % mod;
  return 0;
}
