#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7LL;
const int MAXN = 212345;
int vis[MAXN];
vector<int> g[MAXN];
long long dfs(int u) {
  vis[u] = 1;
  long long r = 1;
  for (int v : g[u])
    if (!vis[v]) r += dfs(v);
  return r;
}
long long fexp(long long b, long long e) {
  if (b == 1 || e == 0) return 1;
  if (b == 0) return 0;
  long long resp = fexp(b, e / 2);
  resp = ((resp % MOD) * (resp % MOD)) % MOD;
  if (e & 1) resp = ((resp % MOD) * (b % MOD)) % MOD;
  return resp % MOD;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int n, k;
  cin >> n >> k;
  for (int i = 0, u, v, w; i < n - 1; ++i) {
    cin >> u >> v >> w;
    if (!w) {
      g[u].push_back(v);
      g[v].push_back(u);
    }
  }
  long long r = fexp(n, k);
  for (int i = 1; i <= n; ++i) {
    if (!vis[i]) {
      r = (r % MOD - fexp(dfs(i), k) % MOD) % MOD;
      if (r < 0) r += MOD;
      r %= MOD;
    }
  }
  cout << r << '\n';
  return 0;
}
