#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int maxn = 2e5 + 9;
vector<vector<int> > graph;
int vis[maxn];
int dfs(int node) {
  vis[node] = true;
  int answer = 1;
  for (auto child : graph[node]) {
    if (vis[child]) continue;
    answer += dfs(child);
  }
  return answer;
}
long long binexp(long long a, int b) {
  long long temp = 1;
  while (b > 0) {
    if (b & 1) temp = (temp * a) % mod;
    a = (a * a) % mod;
    b /= 2;
  }
  return temp;
}
void test_case(int tc) {
  int n, k;
  cin >> n >> k;
  int m = n - 1;
  graph.resize(n + 1);
  for (int i = 1; i <= m; ++i) {
    int u, v, b;
    cin >> u >> v >> b;
    if (b == 1) continue;
    graph[u].push_back(v);
    graph[v].push_back(u);
  }
  long long ans = 0;
  for (int i = 1; i <= n; ++i) {
    if (vis[i]) {
      continue;
    }
    long long p = dfs(i);
    ans += (binexp(p, k));
    ans %= mod;
  }
  long long answer = binexp(n, k);
  answer = (answer - ans + mod) % mod;
  cout << answer;
}
int32_t main() {
  ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  int t = 1;
  for (int tc = 1; tc <= t; ++tc) test_case(tc);
}
