#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int MAXN = 1e5 + 15;
vector<int> Graph[MAXN];
bool visited[MAXN];
int T, N, K;
long long Pow(long long a, long long b) {
  long long ans = 1;
  while (b) {
    if (b & 1) {
      ans = ans * a % MOD;
    }
    a = a * a % MOD;
    b >>= 1;
  }
  return ans;
}
void DFS(int v) {
  if (visited[v]) return;
  visited[v] = 1;
  T++;
  for (auto &itr : Graph[v]) {
    DFS(itr);
  }
}
int main() {
  scanf("%d %d", &N, &K);
  memset(visited, 0, sizeof(visited));
  for (int i = 1; i < N; i++) {
    int x, y, c;
    scanf("%d %d %d", &x, &y, &c);
    if (c == 0) {
      Graph[x].push_back(y);
      Graph[y].push_back(x);
    }
  }
  long long Ans = 0;
  for (int i = 1; i <= N; i++) {
    if (visited[i]) continue;
    T = 0;
    DFS(i);
    Ans = (Ans + Pow(T, K)) % MOD;
  }
  Ans = (Pow(N, K) - Ans + MOD) % MOD;
  printf("%I64d\n", Ans);
  return 0;
}
