#include <bits/stdc++.h>
using namespace std;
int n, k, dd[100005];
vector<int> a[100005];
long long res = 0;
void nhap() {
  cin >> n >> k;
  for (int i = 1; i <= n - 1; ++i) {
    int u, v, w;
    cin >> u >> v >> w;
    if (w == 0) {
      a[u].push_back(v);
      a[v].push_back(u);
    }
  }
}
void DFS(int u) {
  dd[u] = 1;
  for (auto v : a[u])
    if (!dd[v]) DFS(v), dd[u] += dd[v];
}
long long Poww(int x, int y) {
  long long temp = 1;
  for (int i = 1; i <= y; ++i) {
    temp *= x;
    if (temp > 1000000007) temp %= 1000000007;
  }
  return temp;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cout.tie(NULL);
  nhap();
  res = Poww(n, k);
  for (int i = 1; i <= n; ++i)
    if (!dd[i]) {
      DFS(i);
      res -= Poww(dd[i], k);
      while (res < 0) res += 1000000007;
    }
  cout << res;
}
