#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
const int M = 1e9 + 7;
int a[N];
int parent[N], rnk[N];
int ct[N];
void make(int v) {
  parent[v] = v;
  rnk[v] = 0;
  ct[v] = 1;
}
int find(int v) {
  if (parent[v] != v) parent[v] = find(parent[v]);
  return parent[v];
}
void Union(int a, int b) {
  a = find(a);
  b = find(b);
  if (a != b) {
    if (rnk[a] < rnk[b]) swap(a, b);
    parent[b] = a;
    ct[a] += ct[b];
    if (rnk[a] == rnk[b]) rnk[a]++;
  }
}
int binexp1(int a, int b, int m) {
  int result = 1;
  while (b > 0) {
    if (b & 1) {
      result = (result * 1LL * a) % m;
    }
    a = (a * 1LL * a) % m;
    b >>= 1;
  }
  return result;
}
int main() {
  int n, k;
  cin >> n >> k;
  for (int i = 0; i <= n; ++i) {
    make(i);
  }
  int ans = binexp1(n, k, M);
  for (int i = 0; i < n - 1; ++i) {
    int u, v, x;
    cin >> u >> v >> x;
    if (x == 0) {
      Union(u, v);
    }
  }
  for (int i = 1; i <= n; ++i) {
    if (find(i) == i) {
      ans = (ans - binexp1(ct[i], k, M) + M) % M;
    }
  }
  cout << ans;
}
