#include <bits/stdc++.h>
using namespace std;
bool visited[10000007];
vector<long long> g[10000007];
long long ct = 0;
long long pow(long long a, long long b, long long m) {
  long long ans = 1;
  while (b) {
    if (b & 1) ans = (ans * a) % m;
    b /= 2;
    a = (a * a) % m;
  }
  return ans;
}
void dfs(long long i) {
  if (visited[i]) return;
  ct++;
  visited[i] = true;
  for (auto &it : g[i]) dfs(it);
}
int32_t main() {
  long long n, k, u, v, x, ct2;
  cin >> n >> k;
  ct2 = pow(n, k, 1000000007);
  for (long long i = 0; i < n - 1; i++) {
    cin >> u >> v >> x;
    if (x == 0) {
      g[u - 1].push_back(v - 1);
      g[v - 1].push_back(u - 1);
    }
  }
  long long ct1 = 0;
  memset(visited, false, sizeof(visited));
  for (long long i = 0; i < n; i++) {
    if (visited[i]) continue;
    ct = 0;
    dfs(i);
    ct2 -= pow(ct, k, 1000000007);
    ;
    ct2 += 1000000007;
    ct2 %= 1000000007;
  }
  cout << ct2;
}
