#include using namespace std; using ll=long long; using vin=vector; using vll=vector; using vvin=vector>; using vvll=vector>; using vstr=vector; using vvstr=vector>; using vch=vector; using vvch=vector>; using vbo=vector; using vvbo=vector>; using vpii=vector>; using pqsin=priority_queue,greater>; #define mp make_pair #define rep(i,n) for(int i=0;i<(int)(n);i++) #define rep2(i,s,n) for(int i=(s);i<(int)(n);i++) #define all(v) v.begin(),v.end() #define decp(n) cout<>=1; } return res; } ll fermat(ll a,ll b,ll m){ return (a%m)*modpow(b,m-2,m)%m; } int main(){ ll n,m,X;cin>>n>>m>>X; init(n); map,ll> road; int x,y;ll z; rep(i,m){ cin>>x>>y>>z; if(same(x,y))continue; unite(x,y); road[mp(min(x,y),max(x,y))]=z; baby[x].push_back(y); baby[y].push_back(x); } babycount(1,-1); ll ans=(ll)0,tmp; rep2(i,1,n+1){ for(auto b:baby[i]){ tmp=min(babynum[i],babynum[b]); ans+=modpow(X,road[mp(min(i,b),max(i,b))])*((tmp*(n-tmp))%inf); ans%=inf; } } cout<