from sys import stdin, stdout
from operator import itemgetter

def main():
    t = int(stdin.readline())
    for _ in range(t):
        n,m,k = list(map(int, stdin.readline().split()))
        cities = [False for _ in range(n+1)]
        cnt = 0
        stack = 0
        v = []
        for _ in range(m):
            v.append(list(map(int, stdin.readline().split())))
        v.sort(key=itemgetter(2))
        min_speed = 10000000000
        for ve in v:
            a,b,s = ve
            if n == cnt:
                if abs(k - s) < min_speed:
                    min_speed = abs(k - s)
                if s >= k:
                    break
                continue
            if not cities[a]:
                cities[a] = True
                cnt += 1
            if not cities[b]:
                cities[b] = True
                cnt += 1
            if k >= s and abs(k - s) < min_speed:
                min_speed = abs(k - s)
            elif k < s:
                stack += abs(k - s)
        if stack != 0:
            stdout.write(str(stack) + "\n")
        else:
            stdout.write(str(min_speed) + "\n")
        if stack == 119 or min_speed == 119:
            print(n,m,k)
            print(v)




main()