#include <bits/stdc++.h>
using namespace std;
vector<long long> v[100005];
long long p[100005] = {0};
long long cnt = 0;
long long power(long long x, long long y, long long p) {
  long long res = 1;
  x = x % p;
  while (y > 0) {
    if (y & 1) res = ((res % p) * (x % p) % p) % p;
    y = y >> 1;
    x = ((x % p) * (x % p)) % p;
  }
  return (res % p);
}
long long dfs(long long x) {
  p[x] = 1;
  cnt++;
  for (long long i = 0; i < v[x].size(); i++) {
    if (p[v[x][i]] == 0) {
      dfs(v[x][i]);
    }
  }
  return cnt;
}
int main() {
  long long n, k, x, y, z;
  vector<long long> c;
  cin >> n >> k;
  for (long long i = 0; i < n - 1; i++) {
    cin >> x >> y >> z;
    if (z == 0) {
      v[x].push_back(y);
      v[y].push_back(x);
    }
  }
  for (long long i = 1; i <= n; i++) {
    cnt = 0;
    if (p[i] == 0) {
      c.push_back(dfs(i));
    }
  }
  long long sum = 0, sum1 = 0;
  for (long long i = 0; i < c.size(); i++) {
    sum = (sum % 1000000007 + power(c[i], k, 1000000007) % 1000000007) %
          1000000007;
    sum1 += c[i];
  }
  sum1 = n - sum1;
  long long ans = (power(n, k, 1000000007) - sum1 - sum);
  while (ans < 0) {
    ans += 1000000007;
  }
  cout << ans;
}
