def find(u):

    if parent[u]==u:
        return u

    parent[u]=find(parent[u])
    return parent[u]





def union(a,b):
    if find(a)!=find(b):
        u=parent[a]
        v=parent[b]

        if size[u]>size[v]:
            parent[v]=u
            size[u]+=size[v]

        else:
            parent[u] = v
            size[v] += size[u]




    return




for _ in range(int(input())):
    n,m,k=map(int,input().split())
    edges=[]
    for j in range(m):
        u,v,s=map(int,input().split())
        edges.append([s,u,v])

    edges.sort()
    ind1=-1
    ind2=-1
    for j in range(m):
        if edges[j][0]>=k:
            ind1=j
            break

    j=m-1
    while(j>=0):
        if edges[j][0]<k:
            ind2=j
            break

        j+=-1

    ans=float("inf")
    if ind1!=-1:

        parent=[i for i in range(n+1)]
        size = [1 for i in range(n + 1)]
        edges1=[]
        for j in edges:
            edges1.append(j)

        req=abs(edges1[ind1][0]-k)
        u,v=edges[ind1][1],edges[ind1][2]
        if find(u)!=find(v):
            union(u,v)
        edges1.pop(ind1)
        cnt=1
        for j in edges1:
            if cnt==n-1:
                break
            val,u, v = j[0],j[1],j[2]

            if find(u)!=find(v):
                union(u,v)
                cnt+=1
                if val>k:
                    req+=(val-k)

        ans=req

    ind1=ind2
    if ind1 != -1:

        parent = [i for i in range(n + 1)]
        size = [1 for i in range(n + 1)]
        edges1 = []
        for j in edges:
            edges1.append(j)

        req = abs(k-edges1[ind1][0])
        u, v = edges[ind1][1], edges[ind1][2]
        if find(u) != find(v):
            union(u, v)
        edges1.pop(ind1)
        cnt = 1
        for j in edges1:
            if cnt == n - 1:
                break
            val, u, v = j[0], j[1], j[2]

            if find(u) != find(v):
                union(u, v)
                cnt += 1
                if val > k:
                    req += (val - k)

        ans = min(ans,req)

    print(ans)


















