#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const long double PI = 4 * atan((long double)1);
long long int get_hash(string s) {
  long long int N = 1000001;
  long long int base[N], A = 11, MD = 1110111110111;
  base[0] = 1;
  for (int i = (1); i < (N); ++i) base[i] = (base[i - 1] * A) % MD;
  long long int hs = 0;
  for (int i = (0); i < (s.size()); ++i) {
    hs += (s[i] * base[i]);
    hs %= MD;
  }
  return hs;
}
long long power(long long a, long long n) {
  long long res = 1;
  while (n) {
    if (n % 2) res = (res % MOD * a % MOD) % MOD;
    a = (a % MOD * a % MOD) % MOD;
    n /= 2;
  }
  return res % MOD;
}
int par(int i, int* dp) {
  if (i == dp[i]) return i;
  return (par(dp[i], dp));
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  int n, k;
  cin >> n >> k;
  int dp[n + 1];
  for (int i = (0); i < (n + 1); ++i) dp[i] = i;
  for (int i = (0); i < (n - 1); ++i) {
    int x, y, c;
    cin >> x >> y >> c;
    if (c == 0) dp[par(x, dp)] = dp[par(y, dp)] = min(par(x, dp), par(y, dp));
  }
  map<int, int> mpa;
  map<int, int>::iterator it;
  for (int i = (1); i < (n + 1); ++i) mpa[par(i, dp)]++;
  long long int ans = 0;
  for (it = mpa.begin(); it != mpa.end(); ++it) {
    int sp = it->second;
    long long int x = power(sp, k) % MOD;
    ans = (ans % MOD + x % MOD) % MOD;
  }
  long long int tot = power(n, k) % MOD;
  cout << (tot - ans + MOD) % MOD;
  return 0;
}
