#include <bits/stdc++.h>
using namespace std;
const long long N = 100100;
const long long Mod = 1e9 + 7;
bool Vis[N];
vector<long long> Adj[N];
void sub(long long& x, long long y) { x = (x - y + 10 * Mod) % Mod; }
long long fp(long long x, long long y) {
  if (!y) return 1;
  long long Res = fp(x, y / 2);
  Res = (Res * Res) % Mod;
  if (y & 1) Res = (x * Res) % Mod;
  return Res;
}
long long DFS(long long i) {
  if (Vis[i]) return 0;
  Vis[i] = true;
  long long Res = 1;
  for (auto j : Adj[i]) Res += DFS(j);
  return Res;
}
int main() {
  long long n, k;
  cin >> n >> k;
  for (long long i = 1; i < n; ++i) {
    long long x, y, w;
    scanf("%I64d%I64d%I64d", &x, &y, &w);
    if (w) continue;
    Adj[x].push_back(y);
    Adj[y].push_back(x);
  }
  long long Ans = fp(n, k);
  for (long long i = 1; i <= n; i++)
    if (!Vis[i]) sub(Ans, fp(DFS(i), k));
  cout << Ans;
}
