#include <bits/stdc++.h>
using namespace std;
vector<vector<long long>> g;
vector<bool> visited;
long long dfs(long long second) {
  visited[second] = 1;
  long long nov = 1;
  for (long long i = 0; i < g[second].size(); i++) {
    if (visited[g[second][i]] == 0) nov += dfs(g[second][i]);
  }
  return nov;
}
int main() {
  long long n, k, u, v, b;
  cin >> n >> k;
  g.resize(n + 1, vector<long long>());
  visited.resize(n + 1, 0);
  for (long long i = 1; i <= n - 1; i++) {
    cin >> u >> v >> b;
    if (b == 0) {
      g[u].push_back(v);
      g[v].push_back(u);
    }
  }
  vector<long long> ans;
  for (long long i = 1; i <= n; i++) {
    if (visited[i] == 0) ans.push_back(dfs(i));
  }
  long long sum = 0;
  for (long long i = 0; i < ans.size(); i++) {
    long long tk = k, mul = 1;
    while (tk--) mul = (mul * ans[i]) % 1000000007;
    sum = (sum + mul) % 1000000007;
  }
  long long tmul = 1;
  while (k--) tmul = (tmul * n) % 1000000007;
  cout << (tmul - sum + 1000000007) % 1000000007;
}
