import sys

def load_sys():
    return sys.stdin.readlines()

def load_local():
    with open('input.txt','r') as f:
        input = f.readlines()
    return input

def f(n,m,k,edges):
    edges.sort(key = lambda x:x[-1])

    UF = {x:x for x in range(1,n+1)}

    def find(x):
        if UF[x] != x:
            UF[x] = find(UF[x])
        return UF[x]

    def union(x,y):
        UF[find(y)] = find(x)
        return

    edges_cnt = 0
    ans = 0

    for i,j,w in edges:
        if w < k:
            if find(i) != find(j):
                union(i,j)
                edges_cnt += 1
        else:
            if edges_cnt >= n-1:
                return min(w-k, k-edges[i-1][-1])
            if find(i) != find(j):
                union(i,j)
                edges_cnt += 1
                ans += w-k
            if edges_cnt >= n-1:
                return ans
    return k-w

input = load_sys()
i = 1

while i < len(input):
    n,m,k = map(int, input[i].split())
    edges = []
    for _ in range(m):
        i += 1
        x,y,w = map(int, input[i].split())
        edges.append((x,y,w))
    i += 1
    print(f(n,m,k,edges))