import sys; input = sys.stdin.buffer.readline sys.setrecursionlimit(10**7) from collections import defaultdict from collections import deque con = 10 ** 9 + 7; INF = float("inf") def getlist(): return list(map(int, input().split())) class UnionFind: def __init__(self, n): self.par = [i for i in range(n + 1)] self.rank = [0] * (n + 1) def find(self, x): if self.par[x] == x: return x else: self.par[x] = self.find(self.par[x]) return self.par[x] def same_check(self, x, y): return self.find(x) == self.find(y) def union(self, x, y): x = self.find(x); y = self.find(y) if self.rank[x] < self.rank[y]: self.par[x] = y else: self.par[y] = x if self.rank[x] == self.rank[y]: self.rank[x] += 1 class Graph(object): def __init__(self): self.graph = defaultdict(list) def __len__(self): return len(self.graph) def add_edge(self, a, b): self.graph[a].append(b) class BFS(object): def __init__(self, graph, s, N): self.g = graph.graph self.Q = deque(); self.Q.append(s) self.dist = [INF] * N; self.dist[s] = 0 self.prev = [None] * N; self.prev[s] = -1 while self.Q: v = self.Q.popleft() for i in self.g[v]: if self.dist[i] == INF: self.dist[i] = self.dist[v] + 1 self.prev[i] = v self.Q.append(i) def topologicalSort(outE, inE, N): W = [1] * N Q = deque() for i in range(N): if inE[i] == 0: Q.append(i) while Q: u = Q.popleft() for v in outE[u]: inE[v] -= 1 W[v] += W[u] if inE[v] == 0: Q.append(v) return W #処理内容 def main(): N, M, X = getlist() UF = UnionFind(N) D = defaultdict(int) G = Graph() for i in range(M): x, y, z = getlist() x -= 1; y -= 1 if not UF.same_check(x, y): UF.union(x, y) G.add_edge(x, y) G.add_edge(y, x) D[(10 ** 6) * x + y] = z D[(10 ** 6) * y + x] = z BF = BFS(G, 0, N) outE = defaultdict(list) inE = defaultdict(int) for i in range(1, N): a, b = i, BF.prev[i] outE[a].append(b) inE[b] += 1 # print(outE) # print(inE) W = topologicalSort(outE, inE, N) # print(W) ans = 0 for i in range(1, N): ans += (N - W[i]) * W[i] * pow(X, D[(10 ** 6) * i + BF.prev[i]], con) ans %= con print(ans) if __name__ == '__main__': main()