#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
const int N = 100005;
bool vis[N];
vector<pair<int, int> > g[N];
long long c = 0;
long long power(long long x, long long y);
long long powerm(long long x, long long y, int mod2);
void seive(bool arr[], int n);
void dfs(int node);
void solve() {
  long long n, k;
  cin >> n >> k;
  for (long long i = 1; i < n; i++) {
    long long x, y, z;
    cin >> x >> y >> z;
    g[x].push_back({y, z}), g[y].push_back({x, z});
  }
  long long ans = power(n, k);
  memset(vis, false, sizeof(vis));
  for (long long i = 1; i < n + 1; i++) {
    c = 0;
    if (!vis[i]) {
      dfs(i);
      ans = (ans - power(c, k) + 1000000007) % 1000000007;
    }
  }
  cout << ans << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  int t = 1;
  while (t--) solve();
}
void dfs(int node) {
  vis[node] = true;
  c++;
  for (auto x : g[node]) {
    if (!vis[x.first] && x.second == 0) {
      dfs(x.first);
    }
  }
}
long long power(long long x, long long y) {
  long long ans = 1;
  while (y) {
    if (y & 1)
      ans = ((long long)(ans % 1000000007) * (long long)(x % 1000000007)) %
            1000000007;
    x = ((long long)(x % 1000000007) * (long long)(x % 1000000007)) %
        1000000007;
    y = y >> 1;
  }
  return ans % 1000000007;
}
long long powerm(long long x, long long y, int mod2) {
  long long ans = 1;
  while (y) {
    if (y & 1) ans = ((long long)(ans % mod2) * (long long)(x % mod2)) % mod2;
    x = ((long long)(x % mod2) * (long long)(x % mod2)) % mod2;
    y = y >> 1;
  }
  return ans % mod2;
}
