class DSU:
    def __init__(self, n):
        self.uf = {i: i for i in range(n)}
        self.rank = {i: 1 for i in range(n)}

    def find(self, x):
        if self.uf[x] != x:
            self.uf[x] = self.find(self.uf[x])
        return self.uf[x]

    def union(self, x, y):
        px, py = self.find(x), self.find(y)
        if px != py:
            if self.rank[px] > self.rank[py]:
                px, py = py, px
            self.rank[py] += self.rank[px]
            self.uf[px] = py
            return True
        return False

import sys
input = sys.stdin.readline

for _ in range(int(input())):
    n, m, k = map(int, input().split())
    A = [list(map(int, input().split())) for _ in range(m)]
    dsu = DSU(n)
    x, y, a = min(A, key=lambda x: (abs(x[2] - k), -x[2]))
    dsu.union(x - 1, y - 1)
    ans = abs(a - k)
    A.sort(key=lambda x: x[2])
    for x, y, a in A:
        if a <= k:
            dsu.union(x - 1, y - 1)
        else:
            if dsu.union(x - 1, y - 1):
                ans += a - k
    print(ans)