#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
const long long N5 = 1e5 + 9;
const long long N6 = 1e6 + 9;
long long pow(long long a, unsigned long long b, long long m) {
  long long ans = 1;
  a = a % m;
  while (b > 0) {
    if (b & 1) {
      ans = (ans * a) % m;
    }
    a = (a * a) % m;
    b = b >> 1;
  }
  return ans;
}
long long modInverse(long long a, long long m) { return pow(a, m - 2, m) % m; }
void init() {}
long long ans = 0;
void DFS(vector<long long> graph[], long long u, long long visited[]) {
  ans++;
  visited[u] = 1;
  for (long long i = 0; i < graph[u].size(); i++) {
    if (visited[graph[u][i]] == 0) DFS(graph, graph[u][i], visited);
  }
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ;
  long long n, k;
  cin >> n >> k;
  vector<long long> graph[n];
  for (long long i = 0; i < n - 1; i++) {
    long long u, v, w;
    cin >> u >> v >> w;
    if (w == 0) {
      graph[u - 1].push_back(v - 1);
      graph[v - 1].push_back(u - 1);
    }
  }
  long long visited[n];
  memset(visited, 0, sizeof(visited));
  long long total = pow(n, k, mod);
  for (long long i = 0; i < n; i++) {
    if (visited[i] == 0) {
      ans = 0;
      DFS(graph, i, visited);
      total = (total - pow(ans, k, mod) + mod) % mod;
    }
  }
  cout << total << endl;
  return 0;
}
