#include <bits/stdc++.h>
template <class C>
inline void log_c(const C& c) {}
template <class C>
inline int sz(const C& c) {
  return static_cast<int>(c.size());
}
using namespace std;
using num = int64_t;
const std::string eol = "\n";
using pii = pair<int, int>;
num sum = 0;
vector<vector<int>> adj;
vector<bool> visited;
const num mod = 1000000000 + 7;
inline num pow_by_mod(num n, num exp) {
  num ax = 1;
  for (; exp; --exp) {
    ax = (ax * n) % mod;
  }
  return ax;
}
inline int tree_size(int u, int p) {
  int ans = 1;
  visited.at(u) = true;
  for (int v : adj.at(u)) {
    if (v == p) continue;
    ans += tree_size(v, u);
  }
  return ans;
}
int main() {
  std::ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  int n, m;
  cin >> n >> m;
  adj.resize(n);
  visited.resize(n);
  for (int k = 0; k < (n - 1); ++k) {
    int u, v, x;
    cin >> u >> v >> x;
    if (x == 0) {
      --u;
      --v;
      adj.at(u).push_back(v);
      adj.at(v).push_back(u);
    }
  }
  num bad_path_count = 0;
  for (int u = 0; u < (n); ++u) {
    if (visited.at(u)) continue;
    num sz = tree_size(u, u);
    bad_path_count = (bad_path_count + pow_by_mod(sz, m)) % mod;
  }
  const num path_count = pow_by_mod(n, m);
  const num good_path_count = (path_count - bad_path_count + mod) % mod;
  cout << good_path_count << endl;
  return 0;
}
