import math
from sys import stdin

def uf_find(n,p):

    ufl = []

    while p[n] != n:
        ufl.append(n)
        n = p[n]

    for i in ufl:
        p[i] = n

    return n


def uf_union(a,b,p,rank):

    ap = uf_find(a,p)
    bp = uf_find(b,p)

    if ap == bp:
        return True
    else:

        if rank[ap] > rank[bp]:
            p[bp] = ap
        elif rank[ap] < rank[bp]:
            p[ap] = bp
        else:
            p[bp] = ap
            rank[ap] += 1

        return False

tt = int(stdin.readline())

for loop in range(tt):

    n,m,k = map(int,stdin.readline().split())

    under = []
    over  = []
    for i in range(m):
        x,y,s = map(int,stdin.readline().split())
        x -= 1
        y -= 1

        if s <= k:
            under.append( (s,x,y) )
        else:
            over.append( (s,x,y) )

    under.sort()
    over.sort()
    ans = float("inf")
    cnt = 0

    p = [i for i in range(n)]
    rank = [0] * n
    for c,x,y in under:
        if not uf_union(x,y,p,rank):
            cnt += 1

    if cnt == n-1 and len(under) > 0:
        ans = min(ans,k-under[-1][0])

    for c,x,y in over:
        if not uf_union(x,y,p,rank):
            cnt += 1
        if cnt == n-1:
            ans = min(ans , c-k)

    print (ans)