/* -*- coding: utf-8 -*- * * 1207.cc: No.1207 グラフX - yukicoder */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; /* constant */ const int MAX_N = 200000; const int MOD = 1000000007; /* typedef */ typedef long long ll; typedef queue qi; typedef pair pii; typedef vector vpii; struct UFT { int links[MAX_N], ranks[MAX_N], sizes[MAX_N]; UFT() {} void init(int n) { for (int i = 0; i < n; i++) links[i] = i, ranks[i] = sizes[i] = 1; } int root(int i) { int i0 = i; while (links[i0] != i0) i0 = links[i0]; return (links[i] = i0); } int rank(int i) { return ranks[root(i)]; } int size(int i) { return sizes[root(i)]; } bool same(int i, int j) { return root(i) == root(j); } int merge(int i0, int i1) { int r0 = root(i0), r1 = root(i1), mr; if (r0 == r1) return r0; if (ranks[r0] == ranks[r1]) { links[r1] = r0; sizes[r0] += sizes[r1]; ranks[r0]++; mr = r0; } else if (ranks[r0] > ranks[r1]) { links[r1] = r0; sizes[r0] += sizes[r1]; mr = r0; } else { links[r0] = r1; sizes[r1] += sizes[r0]; mr = r1; } return mr; } }; /* global variables */ UFT uft; vpii nbrs[MAX_N]; int ps[MAX_N], pws[MAX_N], cns[MAX_N], ss[MAX_N]; /* subroutines */ int powmod(int a, int n) { // a^n % MOD int pm = 1; while (n > 0) { if (n & 1) pm = (ll)pm * a % MOD; a = (ll)a * a % MOD; n >>= 1; } return pm; } /* main */ int main() { int n, m, x; scanf("%d%d%d", &n, &m, &x); uft.init(n); for (int i = 0; i < m; i++) { int xi, yi, zi; scanf("%d%d%d", &xi, &yi, &zi); xi--, yi--; if (! uft.same(xi, yi)) { uft.merge(xi, yi); int wi = powmod(x, zi); nbrs[xi].push_back(pii(yi, wi)); nbrs[yi].push_back(pii(xi, wi)); } } ps[0] = -1; qi q; q.push(0); while (! q.empty()) { int u = q.front(); q.pop(); int up = ps[u]; vpii &nbru = nbrs[u]; for (vpii::iterator vit = nbru.begin(); vit != nbru.end(); vit++) { int v = vit->first; if (v != up) { ps[v] = u; pws[v] = vit->second; cns[u]++; q.push(v); } } } for (int u = 0; u < n; u++) if (cns[u] == 0) q.push(u); int sum = 0; while (! q.empty()) { int u = q.front(); q.pop(); ss[u]++; int up = ps[u]; if (up >= 0) { sum = (sum + (ll)pws[u] * ss[u] % MOD * (n - ss[u]) % MOD) % MOD; ss[up] += ss[u]; if (--cns[up] == 0) q.push(up); } } printf("%d\n", sum); return 0; }