import java.util.*;
import java.io.*;

public class JRoadReform {

	static class road implements Comparable<road>{
		int x, y;
		long s;
		public road(int a, int b, long c) {
			x = a;
			y = b;
			s = c;
		}
		public int compareTo(road e) {
			// TODO Auto-generated method stub
			if(this.s-e.s>0)return 1;
			else if(this.s-e.s<0)return -1;
			return 0;
		}
		public String toString() {
			return x+" "+y+" "+s;
		}
	}
	static int[] parent,sizes;
	static int findParent(int a) {
		if(parent[a]==-1||parent[a]==a)return a;
		return findParent(parent[a]);
	}
	static boolean isConnected(int a, int b) {
		if(findParent(a)==findParent(b))return true;
		return false;
	}
	static void connect(int a, int b) {
		if(isConnected(a,b))return;
		if(sizes[findParent(a)]>sizes[findParent(b)]){
			int temp = a;
			a = b;
			b = temp;
		}
		parent[findParent(a)] = findParent(b);
		sizes[findParent(b)]+=sizes[findParent(a)];
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		FastReader sc = new FastReader();
		int t = sc.nextInt();
		while(t-->0) {
			int n = sc.nextInt(), m = sc.nextInt(), k = sc.nextInt();
			PriorityQueue<road> roads = new PriorityQueue<>();
			ArrayList<road> mst = new ArrayList<>();
			parent = new int[n+1]; sizes = new int[n+1];
			Arrays.fill(parent, -1);
			int min = Integer.MAX_VALUE, s1 = -1, x1 = -1, y1 = -1;
			for(int i = 0; i<m; i++) {
				int x = sc.nextInt(), y = sc.nextInt(), s = sc.nextInt();
				roads.add(new road(x,y,s));
				min = Math.min(Math.abs(s-k), min);
			}
			boolean good = true;
			long total  = 0;
			for(road cur : roads) {
				if(!isConnected(cur.x,cur.y)) {
					connect(cur.x, cur.y);
					mst.add(cur);
					if(cur.s>k) {
						good = false;
						total+=cur.s-k;
					}
				}
			}
			System.out.println(good?min:total);
		}
	}

	public static class FastReader {
		BufferedReader br;
		StringTokenizer st;

		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		String nextLine() {
			String str = null;
			try {
				str = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return str;
		}
	}
}
