# -*- coding: utf-8 -*-
"""
Created on Sun Jan 10 14:02:20 2021

@author: kissz
"""
#import sys

def main(input_fcn=input):
    for _ in range(int(input_fcn())):
        #print('new test',file=sys.stderr)
        n,m,k=map(int,input_fcn().split())
        roads=[(0,0,0)]*m
        for i in range(m):
            s,d,lim=map(int,input_fcn().split())
            roads[i]=(lim,s,d)
            
        roads.sort()
        #print(roads,file=sys.stderr)
        lim,s,d=roads[0]
        res=max(0,lim-k)
        connected=set([s,d])
        if len(connected)<n:
            for lim,s,d in roads:
                if (s in connected)+(d in connected)==1:
                    connected.update([s,d])
                    res+=max(0,lim-k)
                    #print(s,d,lim,file=sys.stderr)
                    if len(connected)==n: break
        if lim<k: res+=min(abs(k-lim) for lim,_,_ in roads)        
        print(res)
        
        

if __name__=='__main__':
    main()
else:
    import sys
