#include <bits/stdc++.h>
using namespace std;
const long long N = 2e5 + 5;
const long long MOD = 1e9 + 7;
long long powe(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;
}
long long n, k, sz, ans = 0;
bool vis[N];
vector<long long> g[N];
void dffs(long long u) {
  if (vis[u]) return;
  sz++;
  vis[u] = 1;
  for (auto &it : g[u]) dffs(it);
}
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  cin >> n >> k;
  long long ans = powe(n, k, MOD);
  for (long long i = 1; i <= n - 1; i++) {
    long long u, v, x;
    cin >> u >> v >> x;
    if (x == 0) g[u].push_back(v), g[v].push_back(u);
  }
  for (long long i = 1; i <= n; i++) {
    if (vis[i]) continue;
    sz = 0;
    dffs(i);
    ans -= powe(sz, k, MOD);
    ans += MOD;
    ans %= MOD;
  }
  cout << ans;
  return 0;
}
