#include <bits/stdc++.h>
using namespace std;
long long par[200000];
long long ran[200000];
long long cnt[200000];
void init(long long n) {
  for (long long i = 0; i <= n; i++) {
    par[i] = i;
    ran[i] = 0;
  }
}
long long finds(long long x) {
  if (par[x] == x)
    return x;
  else
    return par[x] = finds(par[x]);
}
void unite(long long x, long long y) {
  x = finds(x);
  y = finds(y);
  if (x == y) return;
  if (ran[x] < ran[y]) {
    par[x] = y;
  } else {
    par[y] = x;
    if (ran[x] == ran[y]) ran[x]++;
  }
}
long long quick_mod(long long a, long long n) {
  long long tmp = a;
  long long ans = 1;
  while (n) {
    if (n % 2 == 1) ans = (tmp * ans) % 1000000007;
    n /= 2;
    tmp = (tmp * tmp) % 1000000007;
  }
  return ans;
}
int main() {
  long long n, k;
  scanf("%lld%lld", &n, &k);
  init(n);
  for (long long i = 0; i < n - 1; i++) {
    long long a, b, c;
    scanf("%lld%lld%lld", &a, &b, &c);
    if (c == 0) unite(a, b);
  }
  for (long long i = 1; i <= n; i++) {
    finds(i);
    cnt[par[i]]++;
  }
  long long ans = quick_mod(n, k);
  for (long long i = 1; i <= n; i++) {
    ans = (ans + 1000000007 - quick_mod(cnt[i], k)) % 1000000007;
  }
  printf("%lld\n", ans);
}
