#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")

#include<bits/stdc++.h>

using namespace std;
#define ll long long
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define lb lower_bound
#define ub upper_bound
#define ins insert
#define ull unsigned long long
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define ff first
#define ss second
#define fly ios::sync_with_stdio(0) , cin.tie(0) , cout.tie(0);
#define nl "\n"
#define sz(a) (int)(a).size()
#define all(a) (a).begin(),(a).end()
#define fl(a,x) memset(a,x,sizeof(a));
#define pt(a,x) cout << get<x>(a) << " " ;
#define mt make_tuple
#define vec vector
#define ld long double
#define eps 1e-9

#define int long long

const int mod = (int) 1e9 + 7 ;
const int MOD = (int) 998244353 ;
const int INF = (int) 1e18 ;

typedef vector<int> vii;
typedef pair<int,int> pii;
typedef vector<pii> vpi;
typedef vector<vector<int> > vv;

#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }

void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
    cerr << *it << " = " << a << endl;
    err(++it, args...);
}

const int N = 2e5 + 5; 
int par[N], rnk[N]; 

struct edge {
	int u, v, wt ; 
	const bool operator < (const edge &other) const {
		return wt < other.wt; 
	}
};

int find_set(int v) {
	if(v == par[v]) return v ; 
	return par[v] = find_set(par[v]) ;
}

void union_set(int a, int b) {
	a = find_set(a) ; 
	b = find_set(b) ; 
	if(a != b) {
		if(rnk[a] < rnk[b]) swap(a, b) ; 
		par[b] = a ; 
		if(rnk[a] == rnk[b]) ++rnk[a] ; 
	}
}

void solve() {

	int n, m, k; cin >> n >> m >> k ;
	rep(i,1,n+1) par[i] = i, rnk[i] = 0 ; 

	vec<edge> e ; 
	rep(i,0,m) {
		int u, v, w; cin >> u >> v >> w; 
		e.pb({u,v,w}) ;
	}

	sort(all(e)) ; 

	int mx = 0, ans = 0 ; 
	for(auto i : e) {
		if(find_set(i.u) != find_set(i.v)) {
			mx = max(mx, i.wt) ; 
			ans += max(0ll, i.wt-k) ; 
			union_set(i.u, i.v) ; 
		}
	}

	if(mx >= k) cout << ans << nl ;
	else {
		ans = INF ; 
		for(auto i : e) {
			ans = min(ans, abs(k-i.wt)) ;
		}
		cout << ans << nl ;
	}
}

int32_t main() {

#ifdef LOCAL
    freopen("error.txt", "w", stderr);
#endif

    fly;
    int t; cin >> t; while(t--)
        solve() ;

    // cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
    return 0;
}
