from heapq import *
class dsu:
    def __init__(self):
        self.parent=[0]*(10**6)
        self.size=[0]*(10**6)
    def make_set(self,v):
        self.parent[v]=v
        self.size[v]=1
    def union_set(self,a,b):
        a=self.find_set(a)
        b=self.find_set(b)
        if (a!=b):
            if self.size[a]<self.size[b]:
                a,b=b,a
            self.parent[b]=a

            self.size[a]+=self.size[b]
    def find_set(self,v):
        if (v==self.parent[v]):
            return v
        self.parent[v]=self.find_set(self.parent[v])
        return self.parent[v]
for _ in range(int(input())):
    n,m,k=map(int,input().split())
    xx=dsu()

    for i in range(1,n+1):
        xx.make_set(i)

    z=[]
    for i in range(m):

        x,y,s=map(int,input().split())
        z.append([abs(s-k),x,y])
    heapify(z)
    c=10**20
    while (z):
        i=heappop(z)
        #print(i)


        if xx.find_set(i[1])==xx.find_set(i[2]):
            pass
        else:
            xx.union_set(i[1],i[2])
            c=min(c,i[0])

    print(c)