#include <bits/stdc++.h>
using namespace std;
long long power(long long a, long long b, long long m) {
  long long ans = 1;
  a %= m;
  while (b) {
    if (b & 1) ans = (ans * a) % m;
    a = (a * a) % m;
    b >>= 1;
  }
  return ans;
}
vector<long long> adj[100009];
bool vis[100009];
long long sz = 0;
void dfs(int i) {
  vis[i] = true;
  sz++;
  for (auto v : adj[i]) {
    if (vis[v] == false) dfs(v);
  }
}
int main() {
  std::ios_base::sync_with_stdio(false);
  cin.tie(0);
  cin.tie(0);
  memset(vis, false, sizeof(vis));
  unsigned long long n, k, u, v, c;
  cin >> n >> k;
  for (long long i = 1; i < n; ++i) {
    cin >> u >> v >> c;
    if (c == 0) {
      adj[u].push_back(v);
      adj[v].push_back(u);
    }
  }
  long long ans = (power(n, k, 1000000007) - n) % 1000000007;
  for (long long i = 1; i <= n; ++i) {
    if (vis[i] == false) {
      sz = 0;
      dfs(i);
      ans += 1000000007;
      ans -= power(sz, k, 1000000007);
      ans += sz;
      ans = ans % 1000000007;
    }
  }
  ans = ans % 1000000007;
  while (ans < 0) {
    ans += 1000000007;
  }
  cout << ans;
  return 0;
}
