#include <bits/stdc++.h>
using namespace std;
long long int parent[(int)1e5 + 2], size_dsu[(int)1e5 + 2], n, k;
string get_string() {
  string s;
  getline(cin >> ws, s);
  return s;
}
void init_edge(long long int u) {
  parent[u] = u;
  size_dsu[u] = 1;
}
long long int find_parent(long long int u) {
  if (u == parent[u]) {
    return u;
  }
  return parent[u] = find_parent(parent[u]);
}
void union_dsu(long long int u, long long int v) {
  u = find_parent(u);
  v = find_parent(v);
  if (u != v) {
    if (size_dsu[u] > size_dsu[v]) {
      parent[v] = u;
      size_dsu[u] += size_dsu[v];
    } else {
      parent[u] = v;
      size_dsu[v] += size_dsu[u];
    }
  }
}
long long int modulo_pow(long long int x, long long int y, long long int p) {
  long long int res = 1;
  x = x % p;
  if (x == 0) {
    return 0;
  }
  while (y > 0) {
    if (y % 2 == 1) {
      res = (res * x) % p;
    }
    y = y >> 1;
    x = (x * x) % p;
  }
  return res;
}
void solve() {
  long long int x, y, u, ans;
  cin >> n >> k;
  for (long long int i = 1; i <= n; i++) {
    init_edge(i);
  }
  for (long long int i = 1; i < n; i++) {
    cin >> x >> y >> u;
    if (u != 1) {
      union_dsu(x, y);
    }
  }
  set<long long int> s;
  for (long long int i = 1; i <= n; i++) {
    s.insert(find_parent(i));
  }
  ans = modulo_pow(n, k, (long long int)1e9 + 7);
  for (auto i : s) {
    ans -= modulo_pow(size_dsu[i], k, (long long int)1e9 + 7);
    if (ans < 0) {
      ans += (long long int)1e9 + 7;
    }
  }
  cout << ans << endl;
}
int main(void) {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cout << fixed << showpoint;
  cout << setprecision(9);
  solve();
  return 0;
}
