# https://codeforces.com/problemset/problem/1108/F
# AC

class Union:
    def __init__(self, n):
        self.p    = [i for i in range(n+1)]
        self.rank = [0] * (n+1) 
        
    def find(self, x):
        if self.p[x] != x:
            self.p[x] = self.find(self.p[x])
        return self.p[x]
    
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        
        if x != y:
            if self.rank[x] < self.rank[y]:
                self.p[x]     = y
                self.rank[y] += self.rank[x]
            else:
                self.p[y]     = x
                self.rank[x] += self.rank[y]
            
for _ in range(int(input())):
    
    n, m, k =  map(int, input().split())
    edge    =  [list(map(int, input().split())) for _ in range(m)]
    edge    =  sorted(edge,key=lambda x: x[2])

    U       = Union(n)
    choose, diff = None, float('inf')
    total   = 0 
    
    for i in range(m):
        if abs(edge[i][2] - k) < diff:
            diff   = abs(edge[i][2] - k)
            choose = i
        
    total += abs(edge[choose][2] - k)   
    u, v   = edge[choose][:2]    
    U.union(u, v)

    for i in range(m):
        if i == choose: continue
        u, v, w = edge[i]
    
        if U.find(u) == U.find(v):
            continue
        
        U.union(u, v)
    
        if w > k:
            total +=  abs(w - k)
    
    print(total)        