// Don't place your source in a package
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;






// Please name your class Main
public class Main {
    static Scanner in = new Scanner(System.in);
    public static void main (String[] args) throws java.lang.Exception {
        PrintWriter out = new PrintWriter(System.out);



        int T=Int();
        for(int t=0;t<T;t++){
            int n=Int();
            int m=Int();
            int k=Int();

            int A[][]=new int[m][3];
            for(int i=0;i<A.length;i++){
                A[i][0]=Int()-1;
                A[i][1]=Int()-1;
                A[i][2]=Int();
            }


            Solution sol=new Solution();
            sol.solution(out,A,n,k);
        }
        out.flush();

    }

    public static long Long(){ return in.nextLong();}
    public static int Int(){
        return in.nextInt();
    }
    public static String Str(){
        return in.next();
    }
}



class Solution{
    public void solution(PrintWriter out,int A[][],int n,int k){
        long res=10000000000000000l;
        int nums[]=new int[n];
        List<int[]>list1=new ArrayList<>();
        List<int[]>list2=new ArrayList<>();


        for(int i=0;i<nums.length;i++){
            nums[i]=i;
        }

        for(int i=0;i<A.length;i++){
            if(A[i][2]<=k){
                list1.add(A[i]);
            }
            else{
                list2.add(A[i]);
            }
        }

        Collections.sort(list1,(a,b)->{
            return b[2]-a[2];
        });

        Collections.sort(list2,(a,b)->{
            return a[2]-b[2];
        });

        int cnt=0;

        for(int p[]:list1){
            int v1=p[0],v2=p[1],w=p[2];
            int r1=find(nums,v1);
            int r2=find(nums,v2);
            if(r1!=r2){
                nums[r1]=r2;
                cnt++;
            }
        }

        if(cnt==n-1){
            res=Math.min(res,k-list1.get(0)[2]);
            if(list2.size()>0){
                res=Math.min(res,list2.get(0)[2]-k);
            }
        }
        else{
            long sum=0;
            for(int p[]:list2){
                int v1=p[0],v2=p[1],w=p[2];
                int r1=find(nums,v1);
                int r2=find(nums,v2);
                if(r1!=r2){
                    nums[r1]=r2;
                    cnt++;
                    sum+=w;
                }
            }
            res=sum;
        }


        System.out.println(res);

    }

    public int find(int nums[],int x){
        if(nums[x]==x)return x;
        int root=find(nums,nums[x]);
        nums[x]=root;
        return root;
    }


}
