#include <bits/stdc++.h>
using namespace std;
;
const long long INF64 = 0X3F3F3F3F3F3F3F3F;
const int INF32 = 0x3F3F3F3F;
const int mod = 1e9 + 7;
const int mod2 = 1e9 + 9;
const int N = 2e5 + 2;
long long quickpow(long long a, long long b) {
  long long ans = 1;
  while (b) {
    if (b & 1) ans = a * ans % mod;
    a = a * a % mod;
    b >>= 1;
  }
  return ans;
}
vector<long long> fa, mark;
int ffind(int x) {
  if (x != fa[x]) {
    return fa[x] = ffind(fa[x]);
  }
  return x;
}
void uunion(int x, int y) {
  int a = ffind(x), b = ffind(y);
  if (a < b) swap(a, b);
  fa[b] = a;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  int n, k;
  cin >> n >> k;
  fa.resize(n + 1);
  mark.resize(n + 1);
  for (int i = 0; i <= n; ++i) {
    fa[i] = i;
  }
  long long u, v, t;
  for (int i = 0; i < n - 1; ++i) {
    cin >> u >> v >> t;
    if (!t) uunion(u, v);
  }
  for (int i = 1; i <= n; ++i) ++mark[ffind(i)];
  t = 0;
  for (int i = 1; i <= n; ++i)
    if (mark[i]) t = (t + quickpow(mark[i], k)) % mod;
  cout << (quickpow(n, k) - t + mod) % mod << '\n';
  return 0;
}
