#include using namespace std; struct Unionfind { // tree number vector par; // constructor Unionfind(int n = 1) : par(n, -1) {} // search root int root(int x) { if (par[x] < 0) return x; return par[x] = root(par[x]); } // is same? bool issame(int x, int y) { return root(x) == root(y); } // add // already added, return 0 bool uni(int x, int y) { x = root(x); y = root(y); if (x == y) return 0; if (par[x] > par[y]) swap(x, y); par[x] += par[y]; par[y] = x; return 1; } int size(int x) { return -par[root(x)]; } }; template struct ModInt { int x; constexpr ModInt() : x(0) {} constexpr ModInt(int64_t y) : x(y >= 0 ? y % mod : (mod - (-y) % mod) % mod) {} constexpr ModInt &operator+=(const ModInt &p) noexcept { if ((x += p.x) >= mod) x -= mod; return *this; } constexpr ModInt &operator-=(const ModInt &p) noexcept { if ((x += mod - p.x) >= mod) x -= mod; return *this; } constexpr ModInt &operator*=(const ModInt &p) noexcept { x = (int)(1LL * x * p.x % mod); return *this; } constexpr ModInt &operator/=(const ModInt &p) noexcept { *this *= p.inverse(); return *this; } constexpr ModInt operator-() const { return ModInt(-x); } constexpr ModInt operator+(const ModInt &p) const noexcept { return ModInt(*this) += p; } constexpr ModInt operator-(const ModInt &p) const noexcept { return ModInt(*this) -= p; } constexpr ModInt operator*(const ModInt &p) const noexcept { return ModInt(*this) *= p; } constexpr ModInt operator/(const ModInt &p) const noexcept { return ModInt(*this) /= p; } constexpr bool operator==(const ModInt &p) const noexcept { return x == p.x; } constexpr bool operator!=(const ModInt &p) const noexcept { return x != p.x; } constexpr ModInt inverse() const noexcept { int a = x, b = mod, u = 1, v = 0, t = 0; while (b > 0) { t = a / b; swap(a -= t * b, b); swap(u -= t * v, v); } return ModInt(u); } constexpr ModInt pow(int64_t n) const { ModInt res(1), mul(x); while (n) { if (n & 1) res *= mul; mul *= mul; n >>= 1; } return res; } friend constexpr ostream &operator<<(ostream &os, const ModInt &p) noexcept { return os << p.x; } friend constexpr istream &operator>>(istream &is, ModInt &a) noexcept { int64_t t = 0; is >> t; a = ModInt(t); return (is); } constexpr int get_mod() { return mod; } }; using P = pair; int n, m, x; Unionfind uf; vector dp; vector> g; ModInt<> solve(int now, int par); int main() { cin >> n >> m >> x; uf = Unionfind(n); g.resize(n); for (int i = 0; i < m; ++i) { int a, b, c; cin >> a >> b >> c; if (!uf.issame(--a, --b)) { g[a].push_back(P(b, c)); g[b].push_back(P(a, c)); uf.uni(a, b); } } dp.assign(n, 1); cout << solve(0, -1) << endl; return 0; } ModInt<> solve(int now, int par) { ModInt<> res; for (auto [to, z] : g[now]) if (to != par) { res += solve(to, now); res += ModInt<>(x).pow(z) * dp[to] * (n - dp[to]); dp[now] += dp[to]; } return res; }