#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
const int MOD = 1e9 + 7;
long long mpower(long long x, long long y, long long p) {
  int res = 1;
  x = x % p;
  while (y > 0) {
    if (y & 1) res = (res * x) % p;
    y = y >> 1;
    x = (x * x) % p;
  }
  return res;
}
long long lol = 0;
vector<int> con[N];
bool visit[N] = {0};
void dfs(long long u) {
  if (visit[u]) return;
  visit[u] = 1;
  lol++;
  for (int i = 0; i < con[u].size(); i++) dfs(con[u][i]);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long n, k, ans;
  cin >> n >> k;
  long long l, r, c;
  for (long long i = 1; i <= n - 1; i++) {
    cin >> l >> r >> c;
    if (c == 1) continue;
    con[l].push_back(r);
    con[r].push_back(l);
  }
  ans = mpower(n, k, MOD);
  for (int i = 1; i <= n; i++) {
    if (visit[i]) continue;
    lol = 0;
    dfs(i);
    ans -= mpower(lol, k, MOD);
    ans += MOD;
    ans %= MOD;
  }
  cout << ans;
  return 0;
}
