#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 20, MOD = 1e9 + 7;
int n, k, u, v, c, cnt, ans;
vector<int> adj[2][N];
bool vis[N];
int power(int a, int b) {
  if (b == 0) return 1;
  int ans = power(a, b >> 1);
  ans = (1ll * ans * ans) % MOD;
  if (b & 1) ans = (1ll * ans * a) % MOD;
  return ans;
}
void go(int node, int parent) {
  vis[node] = true;
  cnt++;
  for (auto child : adj[0][node])
    if (child != parent) go(child, node);
}
int main() {
  scanf("%d%d", &n, &k);
  for (int i = 0; i < n - 1; i++) {
    scanf("%d%d%d", &u, &v, &c);
    adj[c][u].push_back(v);
    adj[c][v].push_back(u);
  }
  ans = power(n, k);
  for (int i = 1; i <= n; i++) {
    if (vis[i]) continue;
    cnt = 0;
    go(i, 0);
    ans = (ans - power(cnt, k) + MOD) % MOD;
  }
  printf("%d", ans);
}
