#include <bits/stdc++.h>
using namespace std;
map<long long, long long> visited;
vector<vector<long long>> graph(100005);
map<pair<long long, long long>, long long> color;
long long modpow(long long n, long long p) {
  if (p == 0) {
    return 1;
  }
  if (p % 2 == 0) {
    return (modpow(n, p / 2) * modpow(n, p / 2)) % 1000000007;
  }
  return (n * modpow(n, p - 1)) % 1000000007;
}
long long dfs(long long start) {
  visited[start]++;
  long long smallans = 1;
  for (long long i = 0; i < graph[start].size(); i++) {
    if (visited.count(graph[start][i])) continue;
    pair<long long, long long> p = make_pair(start, graph[start][i]);
    if (color[p] == 1) continue;
    smallans = smallans + dfs(graph[start][i]);
  }
  return smallans;
}
int32_t main() {
  cin.sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ;
  long long n, k;
  cin >> n >> k;
  for (long long i = 0; i < n - 1; i++) {
    long long u, v, c;
    cin >> u >> v >> c;
    graph[u].push_back(v);
    graph[v].push_back(u);
    color[make_pair(u, v)] = c;
    color[make_pair(v, u)] = c;
  }
  long long x = 0;
  for (long long i = 1; i <= n; i++) {
    if (visited.count(i)) continue;
    long long y = dfs(i);
    x = x + modpow(y, k);
    x = x % 1000000007;
  }
  long long ans = modpow(n, k);
  ans = ans - x;
  if (ans < 0) ans = ans + 1000000007;
  cout << ans << "\n";
}
