#include <bits/stdc++.h>

using namespace std;
const int N = 2e5 + 5;
const long long mod = 1e9 + 7;
int adj[N], nxt[N], to[N], col[N], ecnt;

inline void addEdge(int f, int t, int c) {
    ecnt++;
    nxt[ecnt] = adj[f];
    adj[f] = ecnt;
    to[ecnt] = t;
    col[ecnt] = c;
}

using ll=long long;

ll qpow(ll a, ll b) {
    ll ans = 1;
    for (; b; b >>= 1, a = a * a % mod)
        if (b & 1)
            ans = ans * a % mod;
    return ans;
}

bool vis[N];
long long m;

void dfs(int x) {
    vis[x] = true;
    for (int e = adj[x]; e; e = nxt[e])
        if (col[e] == 0 && !vis[to[e]])
            m++, dfs(to[e]);
}

int main() {
    long long n, k;
    scanf("%lld%lld", &n, &k);
    for (int i = 1, u, v, w; i < n; i++) {
        scanf("%d%d%d", &u, &v, &w);
        addEdge(u, v, w);
        addEdge(v, u, w);
    }

    long long ans = qpow(n, k);
    for (int i = 1; i <= n; i++) {
        if (!vis[i]) {
            vis[i] = true;
            m = 1;
            dfs(i);
            ans = (ans - qpow(m, k) + mod) % mod;
        }
    }

    printf("%lld\n", ans);
    return 0;
}