#include <bits/stdc++.h>
using namespace std;
int64_t MOD = 1000000007;
int32_t DFS(int32_t v, vector<vector<int32_t>>& G, vector<bool>& F) {
  F[v] = true;
  int32_t answer = 1;
  for (auto w : G[v]) {
    if (!F[w]) {
      answer += DFS(w, G, F);
    }
  }
  return answer;
}
int64_t POW(int64_t x, int32_t a) {
  if (a == 0) {
    return 0;
  }
  if (a == 1) {
    return x;
  }
  if (a % 2 == 1) {
    return (x * POW(x, a - 1)) % MOD;
  }
  int64_t tmp = POW(x, a / 2);
  return (tmp * tmp) % MOD;
}
int main() {
  int32_t n, k;
  cin >> n >> k;
  vector<vector<int32_t>> G(n);
  for (int32_t _ = 0; _ < n - 1; ++_) {
    int32_t u, v, x;
    cin >> u >> v >> x;
    --u;
    --v;
    if (x == 0) {
      G[u].push_back(v);
      G[v].push_back(u);
    }
  }
  vector<bool> F(n, false);
  int64_t answer = 0;
  for (int32_t i = 0; i < n; ++i) {
    if (!F[i]) {
      int64_t current = static_cast<int64_t>(DFS(i, G, F));
      answer += POW(current, k);
      answer %= MOD;
    }
  }
  answer = (MOD + POW(n, k) - answer) % MOD;
  cout << answer << endl;
  return 0;
}
