#include <bits/stdc++.h>
using namespace std;
vector<unsigned long long> adj[100001];
vector<pair<unsigned long long, unsigned long long> > ans;
unsigned long long vis[100001];
unsigned long long m = 1e9 + 7;
unsigned long long p;
void dfs(unsigned long long v) {
  p++;
  vis[v] = 1;
  for (unsigned long long i = 0; i < adj[v].size(); i++) {
    unsigned long long to = adj[v][i];
    if (!vis[to]) dfs(to);
  }
}
unsigned long long pwr(unsigned long long a, unsigned long long b) {
  unsigned long long ans = 1;
  while (b) {
    if (b & 1) ans = (ans * a) % m;
    b /= 2;
    a = (a * a) % m;
  }
  return ans;
}
void love_for_infinity() {
  unsigned long long n, k, bad = 0;
  cin >> n >> k;
  for (unsigned long long i = 0; i < n - 1; i++) {
    unsigned long long x, y, z;
    cin >> x >> y >> z;
    if (z == 0) {
      adj[x].push_back(y);
      adj[y].push_back(x);
    }
  }
  unsigned long long ans = pwr(n, k);
  for (unsigned long long i = 1; i <= n; i++) {
    if (!vis[i]) {
      p = 0;
      dfs(i);
      ans -= pwr(p, k);
      ans += m;
      ans = ans % m;
    }
  }
  cout << ans;
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  unsigned long long t;
  t = 1;
  while (t--) {
    love_for_infinity();
    cout << endl;
  }
  return 0;
}
