from sys import stdin, stdout


def road_reform(n, m, k, xys_a, d, r):
    xys_a.sort(key=lambda x: x[2])
    ua = [i for i in range(0, n+1)]
    union(ua, r[0], r[1])

    res = d
    for xys in xys_a:
        rx = ufind(ua, xys[0])
        ry = ufind(ua, xys[1])
        if rx != ry:
            union(ua, rx, ry)
            res += max(0, xys[2] - k)
    return res


def ufind(ua, i):
    if ua[i] != i:
        ua[i] = ufind(ua, ua[i])
    return ua[i]


def union(ua, i, j):
    ri = ufind(ua, i)
    rj = ufind(ua, j)
    ua[ri] = rj


t = int(stdin.readline())
for _ in range(t):
    n, m, k = map(int, stdin.readline().split())

    xys_a = []
    d = 10**9
    r = None
    for _ in range(m):
        x, y, s = map(int, stdin.readline().split())
        xys_a.append([x, y, s])
        if abs(k - s) <= d:
            if abs(k - s) < d or k - s < 0:
                d = abs(k - s)
                r = xys_a[-1]

    res = road_reform(n, m, k, xys_a, d, r)
    stdout.write(str(res) + '\n')
