// practice with kaiboy
import java.io.*;
import java.util.*;

public class CF1468J extends PrintWriter {
	CF1468J() { super(System.out); }
	Scanner sc = new Scanner(System.in);
	public static void main(String[] $) {
		CF1468J o = new CF1468J(); o.main(); o.flush();
	}

	static final int INF = 0x3f3f3f3f;
	int[] ds;
	int find(int i) {
		return ds[i] < 0 ? i : (ds[i] = find(ds[i]));
	}
	boolean join(int i, int j) {
		i = find(i);
		j = find(j);
		if (i == j)
			return false;
		if (ds[i] > ds[j])
			ds[i] = j;
		else {
			if (ds[i] == ds[j])
				ds[i]--;
			ds[j] = i;
		}
		return true;
	}
	void main() {
		int t = sc.nextInt();
		while (t-- > 0) {
			int n = sc.nextInt();
			int m = sc.nextInt();
			int k = sc.nextInt();
			ds = new int[n]; Arrays.fill(ds, -1);
			int[] ii = new int[m];
			int[] jj = new int[m];
			int[] aa = new int[m]; int m_ = 0;
			int a_ = INF, c = n;
			while (m-- > 0) {
				int i = sc.nextInt() - 1;
				int j = sc.nextInt() - 1;
				int a = sc.nextInt();
				a_ = Math.min(a_, Math.abs(a - k));
				if (a <= k) {
					if (join(i, j))
						c--;
				} else {
					ii[m_] = i;
					jj[m_] = j;
					aa[m_] = a - k;
					m_++;
				}
			}
			m = m_;
			if (c == 1) {
				println(a_);
				continue;
			}
			Integer[] hh = new Integer[m];
			for (int h = 0; h < m; h++)
				hh[h] = h;
			Arrays.sort(hh, (h1, h2) -> aa[h1] - aa[h2]);
			a_ = 0;
			for (int h = 0; h < m && c > 1; h++) {
				int h_ = hh[h];
				if (join(ii[h_], jj[h_])) {
					c--;
					a_ += aa[h_];
				}
			}
			println(a_);
		}
	}
}
