#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll MOD = 1e9 + 7;
void dfs(int node, vector<vector<pair<int, int>>>& adj, vector<bool>& vu,
         ll& cnt) {
  for (auto& p : adj[node]) {
    if (!vu[p.first] and p.second == 0) {
      vu[p.first] = true;
      ++cnt;
      dfs(p.first, adj, vu, cnt);
    }
  }
}
ll getPow(ll a, ll p) {
  ll ret = 1, cp = a;
  while (p) {
    if (p & 1) ret = (ret * cp) % MOD;
    p >>= 1;
    cp = (cp * cp) % MOD;
  }
  return ret;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n, k, a, b, c;
  cin >> n >> k;
  vector<vector<pair<int, int>>> adj(n + 1);
  for (int i = 1; i < n; ++i) {
    cin >> a >> b >> c;
    adj[a].emplace_back(b, c);
    adj[b].emplace_back(a, c);
  }
  vector<bool> vu(n + 1);
  ll ans = getPow(n, k);
  for (int i = 1; i <= n; ++i) {
    if (!vu[i]) {
      ll tmp = 1;
      vu[i] = true;
      dfs(i, adj, vu, tmp);
      ans = (ans - getPow(tmp, k)) % MOD;
    }
  }
  cout << (ans + MOD) % MOD;
  return 0;
}
