#include <bits/stdc++.h>
using namespace std;
template <typename T>
bool uax(T &a, const T b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}
template <typename T>
bool uin(T &a, const T b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}
template <typename T1, typename T2>
istream &operator>>(istream &in, pair<T1, T2> &p) {
  in >> p.first >> p.second;
  return in;
}
template <typename T1, typename T2>
ostream &operator<<(ostream &out, pair<T1, T2> &p) {
  out << p.first << ' ' << p.second;
  return out;
}
mt19937 rnd(1928);
const long long MOD = 1e9 + 7;
long long n, k;
vector<vector<pair<int, bool>>> g;
vector<int> used;
vector<long long> szc;
void dfs(int v) {
  szc.back()++;
  for (int i = 0; i < g[v].size(); i++) {
    if (used[g[v][i].first] == 0 && !g[v][i].second) {
      used[g[v][i].first] = used[v];
      dfs(g[v][i].first);
    }
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout << fixed << setprecision(15);
  cin >> n >> k;
  g.resize(n);
  used.resize(n);
  int x, y, z;
  for (int i = 0; i < n - 1; i++) {
    cin >> x >> y >> z;
    x--;
    y--;
    g[x].push_back(make_pair(y, z));
    g[y].push_back(make_pair(x, z));
  }
  int cnt = 1;
  for (int i = 0; i < n; i++) {
    if (used[i] == 0) {
      szc.push_back(0);
      used[i] = cnt++;
      dfs(i);
    }
  }
  long long ans = 1;
  for (int i = 0; i < k; i++) {
    ans = (ans * n) % MOD;
  }
  for (int i = 0; i < szc.size(); i++) {
    long long x = 1;
    for (int j = 0; j < k; j++) {
      x = (x * szc[i]) % MOD;
    }
    ans = (ans - x + MOD) % MOD;
  }
  cout << ans;
}
