#include <bits/stdc++.h>
using namespace std;
const int MAX = 2e5 + 5;
const int MOD = 1e9 + 7;
int n, k, god, visited[MAX];
long long result;
vector<int> adjlist[MAX];
class fastio {
 public:
  fastio() {
    ios_base::sync_with_stdio(false);
    cout.tie(nullptr);
    cin.tie(nullptr);
  }
} __fastio;
long long power(int x) {
  long long tmp = 1;
  for (int i = 1; i <= k; i++) (tmp *= x) %= MOD;
  return tmp;
}
void create_graph(int u, int v) {
  adjlist[u].push_back(v);
  adjlist[v].push_back(u);
}
void dfs(int node) {
  god++;
  visited[node] = 1;
  for (int i = 0; i < adjlist[node].size(); i++) {
    if (!visited[adjlist[node][i]]) dfs(adjlist[node][i]);
  }
}
void solve() {
  cin >> n >> k;
  for (int i = 1; i < n; i++) {
    int u, v, c;
    cin >> u >> v >> c;
    if (c == 0) create_graph(u, v);
  }
  int total = power(n);
  for (int i = 1; i <= n; i++) {
    if (visited[i]) continue;
    god = 0;
    dfs(i);
    total = (total - power(god) + MOD) % MOD;
  }
  cout << total << endl;
}
int main() {
  __fastio;
  solve();
  return 0;
}
