#include <bits/stdc++.h>
using namespace std;
const long long MAXN = 2e6 + 10, inf = 1e18, mod = 1e9 + 7;
struct pair_hash {
  template <class T1, class T2>
  std::size_t operator()(const std::pair<T1, T2> &p) const {
    auto h1 = std::hash<T1>{}(p.first);
    auto h2 = std::hash<T2>{}(p.second);
    return h1 ^ h2;
  }
};
long long pw(long long te, long long tee) {
  if (tee == 0) return 1;
  long long res = pw(te, tee / 2) % mod;
  return (tee % 2 ? (((te * res) % mod) * res) % mod : (res * res) % mod);
}
long long v, u, c, n, k, cnt, p[MAXN];
bool mark[MAXN];
vector<long long> e[MAXN];
void Read_input() {
  cin >> n >> k;
  for (long long i = 1; i < n; i++) {
    cin >> v >> u >> c;
    if (c != 1) e[u].push_back(v), e[v].push_back(u);
  }
}
void dfs(long long v, bool f) {
  cnt += f;
  p[cnt]++;
  mark[v] = true;
  for (auto i : e[v])
    if (!mark[i]) dfs(i, false);
}
void Solve() {
  for (long long i = 1; i <= n; i++)
    if (!mark[i]) dfs(i, true);
  long long t = 0;
  for (long long i = 1; i <= cnt; i++) t = (t + (pw(p[i], k) % mod)) % mod;
  cout << (((pw(n, k) - t) % mod + mod) % mod);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  Read_input(), Solve();
  return 0;
}
