#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5, mod = 1e9 + 7;
vector<pair<int, int> > v[N];
bool vis[N] = {};
int dfs(int node, int par) {
  int ret = 1;
  vis[node] = true;
  for (auto u : v[node]) {
    if (u.first == par || u.second) continue;
    ret += dfs(u.first, node);
  }
  return ret;
}
long long fast_pow(int base, int power) {
  if (!power) return 1;
  long long answer = fast_pow(base, power / 2) % mod;
  answer *= answer;
  if (answer >= mod) answer %= mod;
  if (power & 1) answer *= base;
  if (answer >= mod) answer %= mod;
  return answer;
}
int main() {
  ios::sync_with_stdio(0), ios_base::sync_with_stdio(0), cin.tie(0),
      cout.tie(0);
  ;
  int n, k;
  cin >> n >> k;
  for (int i = 1; i <= (int)n - 1; ++i) {
    int a, b, x;
    cin >> a >> b >> x;
    v[a].push_back({b, x});
    v[b].push_back({a, x});
  }
  long long fans = fast_pow(n, k);
  for (int i = 1; i <= (int)n; ++i) {
    if (vis[i]) continue;
    long long ans = dfs(i, i);
    fans = (fans - fast_pow(ans, k) + mod) % mod;
  }
  cout << fans << "\n";
  return 0;
}
