# -*- coding:utf-8 -*-

"""

created by shuangquan.huang at 2021/1/4

"""

import collections
import time
import os
import sys
import bisect
import heapq
import itertools
from functools import lru_cache
from typing import List



def solve(n, m, k, edges):
    edges.sort()
    
    smaller = [(s, u, v) for s, u, v in edges if s <= k]
    larger = [(s, u, v) for s, u, v in edges if s > k]
    parent = [i for i in range(n+1)]
    
    def find(u):
        pu = parent[u]
        if pu == u:
            return pu
        parent[u] = find(pu)
        return parent[u]
    
    def merge(u, v):
        pu, pv = find(u), find(v)
        parent[pu] = pv
        return pu != pv
    
    
    groups = n
    for s, u, v in smaller:
        if merge(u, v):
            groups -= 1
    
    if groups == 1:
        return min(k - smaller[-1][0], larger[0][0] - k if larger else float('inf'))
    
    ans = 0
    for s, u, v in larger:
        if merge(u, v):
            groups -= 1
            ans += s
        if groups == 1:
            return ans
    
    


if __name__ == '__main__':
    T = int(input())
    ans = []
    for ti in range(T):
        n, m, k = map(int, input().strip().split())
        edges = []
        for _ in range(m):
            u, v, s = map(int, input().split())
            edges.append((s, u, v))
        ans.append(solve(n, m, k, edges))
    
    print('\n'.join(map(str, ans)))
    
    
    