from sys import stdin, stdout
from operator import itemgetter
import sys


input = sys.stdin.buffer.readline  # FOR READING PURE INTEGER INPUTS (space separation ok)
t = int(input())
for _ in range(t):
    n,m,k=[int(x) for x in input().split()]
    p = [x for x in range(n+1)]
    stack = 0
    v = []
    for _ in range(m):
        v.append([int(x) for x in input().split()])
    v.sort(key=itemgetter(2))

    weights = []
    for a, b, s in v:
        p1 = p[a]
        while p1 != p[p1]:
            p1 = p[p1]
        p2 = p[b]
        while p2 != p[p2]:
            p2 = p[p2]
        if p1 == p2:
            continue
        p[p2] = p1
        weights.append(s)
    ans = 0
    for w in weights:
        ans += max(0, w - k)
    if ans > 0:
        stdout.write(str(stack) + "\n")
    else:
        min_speed = 10000000000
        for a,b,s in v:
            min_speed =min(min_speed, abs(s-k))
        stdout.write(str(min_speed) + "\n")

