﻿#include <bits/stdc++.h>
using namespace std;
constexpr int inf = 1e9 + 1;
const int maxn = 2e5 + 5;
#define ll long long
struct edge {
	int u, v;
	ll c;
};
int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int t;
	cin >> t;
	while (t--)
	{
		int n, m, k;
		cin >> n >> m >> k;
		vector<int>fa(n + 1);
		for (int i = 1; i <= n; ++i)fa[i] = i;
		function<int(int)> find = [&](int x){return x == fa[x] ? x : fa[x] = find(fa[x]); };
		vector<edge>a(m);
		for (int i = 0; i < m; ++i)
		{
			cin >> a[i].u >> a[i].v >> a[i].c;
		}
		sort(a.begin(), a.end(), [](edge a, edge b) {return a.c < b.c; });
		int cnt = 0;
		ll d = 0, dd = 0;
		for (int i = 0; i < m; ++i)
		{
			int x1 = find(a[i].u), x2 = find(a[i].v);
			if (x1 != x2)
			{
				fa[x1] = x2;
				if (a[i].c > k)dd += a[i].c - k;
				cnt++;
			}
			if (cnt == n - 1 && a[i].c <= k) {
				d = a[i].c;
			}
			if (cnt == n - 1 && a[i].c > k)
			{
				if (!dd) dd = a[i].c - k;
				break;
			}
		}
		//cout << dd << d << endl;
		ll ans = 1e15;
		if (d) ans = min(ans, k - d);
		if(dd) ans = min(ans, dd);
		cout << ans << endl;
	}
	return 0;
}