#include <bits/stdc++.h>
using namespace std;
const long long int mod = 1000000007;
vector<long long int> adj[100005];
long long int visited[100005];
long long int cnt = 0;
long long int power(long long int b, long long int e) {
  long long int ans = 1;
  while (e) {
    if (e & 1) {
      ans = (ans * b) % mod;
    }
    e /= 2;
    b = (b * b) % mod;
  }
  return ans;
}
void dfs(long long int src) {
  if (visited[src]) {
    return;
  }
  cnt++;
  visited[src] = 1;
  for (auto &u : adj[src]) {
    dfs(u);
  }
}
int32_t main() {
  long long int n, k;
  cin >> n >> k;
  long long int ans = power(n, k);
  long long int u, v, c;
  for (long long int i = 0; i < n - 1; i++) {
    cin >> u >> v >> c;
    if (c == 0) {
      adj[u].push_back(v);
      adj[v].push_back(u);
    }
  }
  for (long long int i = 1; i <= n; i++) {
    if (visited[i]) {
      continue;
    }
    cnt = 0;
    dfs(i);
    ans = (ans - power(cnt, k) + mod) % mod;
  }
  cout << ans % mod << "\n";
}
