from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from itertools import accumulate
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
# input = sys.stdin.readline
 
M = mod = 10**9 + 7 
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
 
def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
def li2():return [str(i)[2:-1] for i in input().rstrip().split()]
def li3():return [int(i) for i in st()]


parents = 0
def giveparent(i):
    global parents
    l1 = []
    while parents[i] != i:
        l1.append(i)
        i = parents[i]
    for j in l1:parents[j] = i
    return i
        
for _  in range(val()):
    
    n, m, k = li()
    
    l = []
    ans = float('inf')
    taken = None
    for i in range(m):
        a, b, c = li()
        l.append([a, b, c])
        if abs(c - k) < ans:
            taken = i
            ans = abs(c - k)
    
    a, b, c = l[taken]
    l = l[:taken] + l[taken + 1:]
    # print(l)
    l.sort(key = lambda x : x[-1])
    # print(l)

    visited = set()
    parents = [i for i in range(n + 5)]
    parents[a] = parents[b]
    visited.add(a)
    visited.add(b)
    for a, b, c in l:
        p1 = giveparent(a)
        p2 = giveparent(b)
        
        if p1 == p2:continue
        
        parents[p1] = parents[p2]
        visited.add(a)
        visited.add(b)
        
        if c > k:ans += c - k
        if len(visited) == n:break
    print(ans)