#include //#include //#pragma GCC optimize("Ofast") using namespace std; #define reps(i,s,n) for(int i = s; i < n; i++) #define rep(i,n) reps(i,0,n) #define Rreps(i,n,e) for(int i = n - 1; i >= e; --i) #define Rrep(i,n) Rreps(i,n,0) #define ALL(a) a.begin(), a.end() #define fi first #define se second typedef long long ll; typedef vector vec; typedef vector mat; ll N,M,H,W,Q,K,A,B; string S; typedef pair P; const ll INF = (1LL<<58); template class modint{ public: ll x; constexpr modint(){x = 0;} constexpr modint(ll _x) : x((_x < 0 ? ((_x += (LLONG_MAX / mod) * mod) < 0 ? _x + (LLONG_MAX / mod) * mod : _x) : _x)%mod){} constexpr modint operator-(){ return x == 0 ? 0 : mod - x; } constexpr modint& operator+=(const modint& a){ if((x += a.x) >= mod) x -= mod; return *this; } constexpr modint operator+(const modint& a) const{ return modint(*this) += a; } constexpr modint& operator-=(const modint& a){ if((x -= a.x) < 0) x += mod; return *this; } constexpr modint operator-(const modint& a) const{ return modint(*this) -= a; } constexpr modint& operator*=(const modint& a){ (x *= a.x)%=mod; return *this; } constexpr modint operator*(const modint& a) const{ return modint(*this) *= a; } constexpr modint pow(unsigned long long pw) const{ modint res(1), comp(*this); while(pw){ if(pw&1) res *= comp; comp *= comp; pw >>= 1; } return res; } //以下、modが素数のときのみ constexpr modint inv() const{ return modint(*this).pow(mod - 2); } constexpr modint& operator/=(const modint &a){ (x *= a.inv().x)%=mod; return *this; } constexpr modint operator/(const modint &a) const{ return modint(*this) /= a; } }; #define mod1 998244353 #define mod2 1000000007 using mint = modint; ostream& operator<<(ostream& os, const mint& a){ os << a.x; return os; } using vm = vector; struct edge{ int to, cost; edge(){} edge(int a, int c){ to = a; cost = c; } }; using ve = vector; void dfs(int v, mint &ans, vector &G, vec &size){ size[v] = 1; for(edge e : G[v]){ if(size[e.to] == -1){ dfs(e.to, ans, G, size); ans += mint(K).pow(e.cost) * size[e.to] * (N - size[e.to]); size[v] += size[e.to]; } } } int main() { class union_find{ vector parent, tree_size; public: union_find(unsigned long _n) : parent(_n), tree_size(_n, 1){ for(unsigned long i = 0; i < _n; ++i)parent[i] = i; } ll find(ll x){ while(parent[x] != x)x = parent[x] = parent[parent[x]]; return x; } bool merge(ll a, ll b){ a = find(a); b = find(b); if(a==b) return false; if(tree_size[a] < tree_size[b])swap(a, b); tree_size[a] += tree_size[b]; parent[b] = a; return true; } bool same(ll a, ll b){ a = find(a); b = find(b); return a == b; } }; //uf.mergeのように使う //ufはMAX_N+1でとるか、代入時に0-indexedにする cin>>N>>M>>K; union_find uf(N + 10); vector G(N, ve(0)); rep(i, M){ int x, y, z; cin>>x>>y>>z; --x; --y; if(uf.merge(x, y)){ G[x].emplace_back(y, z); G[y].emplace_back(x, z); } } mint ans(0); vec size(N, -1); dfs(0, ans, G, size); cout<