from sys import *
input = stdin.readline

def root(node):
    while parent[node]>=0:
        node=parent[node]
    return node

def union(x,y):
    x1,x2 = root(x),root(y)
    if parent[x1]<parent[x2]:
        parent[x1]+=parent[x2]
        parent[x2]=x1
    else:
        parent[x2]+=parent[x1]
        parent[x1]=x2

def kruskal():
    diff,costs = 0,0
    for id in range(n-1):
        idx = order[id]
        x,y,cst = u[idx],v[idx],w_sort[id]
        if root(x)!=root(y):
            diff += max(cst-k,0)
            costs=cst
            union(x,y)
    return diff,costs

def minDiff(weight):
    val = k
    for i in range(m):
        if weight[i]<k:
            val = min(val,k-weight[i])
        else:
            return min(val,weight[i]-k)
    return val


for _ in range(int(input())):
    n,m,k = map(int,input().split())
    w,u,v = [],[],[]
    for i in range(m):
        ui,vi,wi = map(int,input().split())
        w.append(wi)
        u.append(ui)
        v.append(vi)

    parent = [-1] * (n + 1)
    w_sort,order = map(list,zip(*sorted([(j,i) for i,j in enumerate(w)])))
    cost, last = kruskal()
    if last<k:
        cost=minDiff(w_sort)
    print(cost)