#include <bits/stdc++.h>
using namespace std;
long long s[100005], ans, n, k, i, u, v, x, cnt;
vector<pair<int, int> > e[100005];
long long mypow(long long a, long long b) {
  if (a == 0) return 0;
  long long ans = 1;
  for (long long j = 1; j <= b; j++) ans = ans * a % 1000000007;
  return ans;
}
void dfs(int u, int fa) {
  int x;
  for (int i = 0; i < e[u].size(); i++) {
    int v = e[u][i].first;
    if (v == fa) {
      x = e[u][i].second;
      continue;
    }
    if (e[u][i].second == 0) s[u]++;
    dfs(v, u);
  }
  if (fa) {
    if (x == 0)
      s[fa] += s[u];
    else {
      s[u]++;
      ans -= mypow(s[u], k);
      cnt += s[u];
    }
  }
}
int main() {
  cin >> n >> k;
  ans = mypow(n, k);
  for (i = 1; i < n; i++) {
    cin >> u >> v >> x;
    e[u].push_back({v, x});
    e[v].push_back({u, x});
  }
  dfs(1, 0);
  if (s[1]) s[1]++;
  ans -= mypow(s[1], k);
  cnt += s[1];
  ans -= n - cnt;
  cout << (ans % 1000000007 + 1000000007) % 1000000007 << endl;
  return 0;
}
