#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
const long long mod = 1e9 + 7;
int n, k;
vector<vector<int> > v(N + 1);
bool vis[N];
long long ksm(long long x, long long n, long long mod) {
  long long res = 1;
  while (n > 0) {
    if (n & 1) res = res * x % mod;
    x = x * x % mod;
    n >>= 1;
  }
  return res;
}
int main() {
  int a, b, c, num;
  long long sum = 0, ans, kk = 0;
  scanf("%d %d", &n, &k);
  for (int i = 0; i < n - 1; i++) {
    scanf("%d %d %d", &a, &b, &c);
    if (c == 0) {
      v[a].push_back(b);
      v[b].push_back(a);
    }
  }
  for (int i = 1; i <= n; i++) {
    if (v[i].size() != 0) {
      num = 1;
      queue<int> q;
      if (!vis[i]) {
        q.push(i);
        vis[i] = true;
      }
      while (!q.empty()) {
        int top = q.front();
        q.pop();
        for (int j = 0; j < v[top].size(); j++) {
          if (!vis[v[top][j]]) {
            q.push(v[top][j]);
            vis[v[top][j]] = true;
            num++;
          }
        }
      }
      if (num != 1) {
        sum += ksm(num, k, mod);
        kk += num;
        sum %= mod;
      }
    }
  }
  ans = ksm(n, k, mod) - sum - (n - kk);
  if (ans < 0) ans = mod + ans;
  printf("%I64d\n", ans);
  return 0;
}
