#include <bits/stdc++.h>
using namespace std;
const long long int M = 1e9 + 7;
const long long int N = 2e5 + 5;
vector<long long int> visited(N, 0);
vector<vector<long long int> > g(N);
long long int sz = 0;
long long int pow(long long int a, long long int b, long long int M) {
  long long int ans = 1;
  while (b) {
    if (b & 1) {
      ans = (ans * a) % M;
    }
    b = b / 2;
    a = (a * a) % M;
  }
  return ans;
}
void dfs(long long int ik) {
  if (visited[ik] == 1) return;
  sz++;
  visited[ik] = 1;
  for (long long int k = 0; k < g[ik].size(); k++) {
    dfs(g[ik][k]);
  }
}
int main() {
  long long int n, k;
  cin >> n >> k;
  long long int ans = pow(n, k, M);
  for (long long int i = 1; i < n; i++) {
    long long int u, v, l;
    cin >> u >> v >> l;
    if (l == 0) {
      g[u].push_back(v);
      g[v].push_back(u);
    }
  }
  for (long long int i = 1; i <= n; i++) {
    if (visited[i] == 1) continue;
    sz = 0;
    dfs(i);
    ans = ans - pow(sz, k, M);
    ans = ans + M;
    ans = ans % M;
  }
  cout << ans << endl;
  return 0;
}
