#include <bits/stdc++.h>
using namespace std;
const int INF = 1000000000;
const int MAX = 100005;
const int MAX1 = 1005;
const int MAX2 = 105;
const int LEN = 105;
const int BASE = 1000000000;
const double EPS = 1e-7;
const int MOD = 1000000007;
int par[100005];
long long pow(long long a, long long b, int m) {
  long long ans = 1;
  while (b) {
    if (b & 1) ans = (ans * a) % m;
    b /= 2;
    a = (a * a) % m;
  }
  return ans;
}
int root(int v) {
  if (par[v] < 0)
    return v;
  else
    return par[v] = root(par[v]);
}
void connect(int u, int v) {
  int n = root(u), m = root(v);
  if (n == m) return;
  if (par[n] < par[m]) {
    par[n] += par[m];
    par[m] = n;
  } else {
    par[m] += par[n];
    par[n] = m;
  }
}
int main(void) {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ifstream in("");
  ofstream out("");
  clock_t begin = clock();
  for (int i = (0); i < (100005); ++i) par[i] = -1;
  int n, k;
  cin >> n >> k;
  for (int i = (0); i < (n - 1); ++i) {
    int a, b, c;
    cin >> a >> b >> c;
    if (c == 0) {
      connect(a, b);
    }
  }
  long long res = 0;
  set<int> S;
  for (int i = (1); i < (n + 1); ++i) {
    int r = root(i);
    if (S.find(r) != S.end()) continue;
    S.insert(r);
    res += pow(-1 * (long long)par[r], (long long)k, MOD);
  }
  cout << ((pow(n, k, MOD) - res) % MOD + MOD) % MOD << '\n';
  clock_t end = clock();
  double esecs = double(end - begin) / CLOCKS_PER_SEC;
  return 0;
}
