#include <bits/stdc++.h>
using namespace std;
const long long maxn = 1e5 + 1;
vector<long long> tr[maxn];
long long visited[maxn];
long long dfs(long long i) {
  visited[i] = 1;
  long long y = 0;
  for (long long x : tr[i]) {
    if (!visited[x]) y += dfs(x);
  }
  return 1 + y;
}
void solve() {
  long long n, k;
  cin >> n >> k;
  vector<long long> v;
  memset(visited, 0, sizeof(visited));
  for (long long i = 0; i < n - 1; ++i) {
    long long x, y, w;
    cin >> x >> y >> w;
    if (w == 1) continue;
    tr[x].push_back(y);
    tr[y].push_back(x);
  }
  for (long long i = 1; i <= n; ++i) {
    long long ct = 0;
    if (!visited[i]) ct = dfs(i);
    if (ct != 0) v.push_back(ct);
  }
  long long ans = 1;
  for (long long i = 0; i < k; ++i) (ans *= n) %= 1000000007;
  long long xx = 0;
  for (long long x : v) {
    long long y = 1;
    for (long long i = 0; i < k; ++i) (y *= x) %= 1000000007;
    (xx += y) %= 1000000007;
  }
  cout << (ans - xx + 1000000007) % 1000000007 << endl;
}
signed main() {
  ios_base::sync_with_stdio(0), cin.tie(0);
  long long t = 1;
  for (long long i = 1; i <= t; ++i) {
    solve();
  }
  return 0;
}
