class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))

    def find(self, a):
        acopy = a
        while a != self.parent[a]:
            a = self.parent[a]
        while acopy != a:
            self.parent[acopy], acopy = a, self.parent[acopy]
        return a

    def merge(self, a, b):
        self.parent[self.find(b)] = self.find(a)


def kruskal(n, U, V, W):
    union = UnionFind(n)
    cost, merge_cnt = 0, 0
    mst_u, mst_v,rej = [], [],[]
    order = sorted(range(len(W)), key=lambda x: W[x])
    for i in range(len(W)):
        u, v ,w= U[order[i]], V[order[i]],W[order[i]]
        find_u, find_v = union.find(u), union.find(v)
        if find_u != find_v:
            cost += W[order[i]]
            merge_cnt += 1
            union.parent[find_v] = find_u
            mst_u.append(w)
        else:
            rej.append(w)
    rej.sort()
    return  mst_u ,rej
for _ in range(int(input())):
    n,m,k=map(int,input().split())
    X=[]
    Y=[]
    W=[]
    for _ in range(m):
        xi,yi,wi=map(int,input().split())
        X.append(xi);Y.append(yi);W.append(wi)
    u,v=kruskal(len(X)+2,X,Y,W)
    ans=0
    closest1=100000
    closest2=0
    for i in v:
        if i>=k:
            closest1=min(closest1,i)
        else:closest2=max(closest2,i)
    if closest1-k<k-closest2:
        closest=closest1
    else:closest=closest2
    flag=0
    for i in u:
        if i>=k:
            flag=1
            ans+=(i-k)
    if not flag:
        ans=abs(closest-k)
        for i in u:
             ans=min(ans,k-i)
    print(ans)
