#include <bits/stdc++.h>
using namespace std;
const long long INF = 2147483647;
const long long INFL = 9223372036854775807LL;
const double EPSILON = 0.00000001;
const long long MOD = 1000000007;
vector<long long> adj[100000 + 5];
bool visited[100000 + 5];
long long mod_pow(long long b, long long e, long long mod) {
  long long r = 1, q = b;
  while (e) {
    if (e & 1) r = (r * q) % mod;
    q = (q * q) % mod;
    e >>= 1;
  }
  return r;
}
long long search(long long start) {
  long long cnt = 0;
  queue<long long> q;
  q.push(start);
  visited[start] = true;
  while (not q.empty()) {
    long long top = q.front();
    q.pop();
    cnt++;
    for (long long x : adj[top]) {
      if (not visited[x]) {
        visited[x] = true;
        q.push(x);
      }
    }
  }
  return cnt;
}
int32_t main() {
  long long n, k;
  cin >> n >> k;
  for (long long i = 0; i < n - 1; i++) {
    long long u, v, x;
    scanf("%I64d", &u);
    ;
    scanf("%I64d", &v);
    ;
    scanf("%I64d", &x);
    ;
    u--;
    v--;
    if (x == 0) {
      adj[u].push_back(v);
      adj[v].push_back(u);
    }
  }
  long long tot = mod_pow(n, k, MOD);
  long long bad = 0;
  memset(visited, false, sizeof(visited));
  ;
  for (long long i = 0; i < n; i++) {
    if (not visited[i]) {
      long long cnt = search(i);
      bad += mod_pow(cnt, k, MOD);
      bad %= MOD;
    }
  }
  long long good = tot - bad;
  cout << (((good) % (MOD) + MOD) % MOD) << endl;
  return 0;
}
