#include <bits/stdc++.h>
using namespace std;
template <class A, class B>
inline bool mina(A &first, B second) {
  return (first > second) ? (first = second, 1) : 0;
}
template <class A, class B>
inline bool maxa(A &first, B second) {
  return (first < second) ? (first = second, 1) : 0;
}
const int MAXN = 100005;
const int MOD = 1000000007;
int N, M;
vector<int> adj[MAXN];
bool visited[MAXN];
int cnt = 0;
void dfs(int at) {
  cnt++;
  visited[at] = true;
  for (auto first : adj[at]) {
    if (!visited[first]) {
      dfs(first);
    }
  }
}
int my_power(long long b, long long e) {
  long long ret = 1;
  while (e) {
    if (e & 1) ret *= b;
    ret %= MOD;
    b *= b;
    b %= MOD;
    e >>= 1;
  }
  return ret;
}
int main() {
  int u, v, c;
  cin >> N >> M;
  for (int i = 0; (i) < (N - 1); ++(i)) {
    scanf("%d %d %d", &u, &v, &c);
    u--, v--;
    if (c == 0) {
      adj[u].push_back(v);
      adj[v].push_back(u);
    }
  }
  int ans = 0;
  for (int i = 0; (i) < (N); ++(i)) {
    if (!visited[i]) {
      cnt = 0;
      dfs(i);
      ans += my_power(cnt, M);
      ans %= MOD;
    }
  }
  ans = my_power(N, M) - ans + MOD;
  ans %= MOD;
  cout << ans << endl;
  return 0;
}
