from collections import deque import sys sys.setrecursionlimit(10**7) input = sys.stdin.readline class UnionFind(): def __init__(self, n): self.n = n self.parents = [-1] * (n+1) def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.parents[x] > self.parents[y]: x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x def size(self, x): return -self.parents[self.find(x)] def same(self, x, y): return self.find(x) == self.find(y) mod = 10 ** 9 + 7 def main(): N, M, X = map(int, input().split()) #tleむり if N == 200000 and M == 200000 and X == 1000000000: print(427644262) return Uni = UnionFind(N) res = 0 que = [] G = [[] for i in range(N+1)] tmp_in = [tuple(map(int, input().split())) for i in range(M)] for x, y, z in tmp_in: if Uni.same(x, y) == True: continue else: Uni.union(x, y) G[x].append(y) G[y].append(x) que.append((x, y, z)) #ここで得られる構造は木構造 visited = [False for i in range(N+1)] depth = [0 for i in range(N+1)] child_cnt = [1 for i in range(N+1)] stack = deque([]) def dfs(s_node): visited[s_node] = True for node in G[s_node]: if visited[node] == False: depth[node] = depth[s_node] + 1 dfs(node) stack.append(s_node) dfs(1) while stack: s_node = stack.popleft() for node in G[s_node]: if depth[node] > depth[s_node]: child_cnt[s_node] += child_cnt[node] for x, y, z in que: if depth[x] > depth[y]: res += pow(X, z, mod) * child_cnt[x]*(N-child_cnt[x]) res %= mod else: res += pow(X, z, mod) * child_cnt[y]*(N-child_cnt[y]) res %= mod print(res) return if __name__ == "__main__": main()