#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
const long long int M = 1e9 + 7;
bool u[N];
int s;
vector<vector<int>> a;
void dfs(int x) {
  if (u[x]) return;
  u[x] = 1;
  s++;
  for (int y : a[x])
    if (!u[y]) dfs(y);
}
long long int powM(long long int b, int p) {
  long long int r = 1;
  for (; p; b = b * b % M, p /= 2)
    if (p & 1) r = r * b % M;
  return r;
}
void solve() {
  int n, k;
  cin >> n >> k;
  a = std::vector<std::vector<int>>(n);
  for (int i = 0; i < n - 1; ++i) {
    int u, v, x;
    cin >> u >> v >> x;
    u--, v--;
    if (!x) a[u].push_back(v), a[v].push_back(u);
  }
  long long int ans = powM(n, k);
  for (int i = 0; i < n; ++i) {
    if (u[i]) continue;
    s = 0;
    dfs(i);
    ans -= powM(s, k);
    ans += M;
    ans %= M;
  }
  cout << ans;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  solve();
  cout << "\n";
  return 0;
}
