#include <bits/stdc++.h>
using namespace std;
int n,m,k,par[200001];

int find(int curr){
    return curr == par[curr] ? curr : par[curr] = find(par[curr]);
}

void solve(){
    cin >> n >> m >> k;
    for(int i = 1 ; i <= n ; i += 1){
        par[i] = i;
    }
    long long mini = 10000000000;
    vector<pair<int,pair<int,int>>> all;
    for(int i = 0 ; i < m ; i += 1){
        int a,b,c;
        cin >> a >> b >> c;
        mini = min(mini,(long long)abs(c-k));
        all.push_back({max(c-k,-1),{a,b}});
    }
    sort(all.begin(),all.end());
    long long ans = 0;
    int maxi = 0;
    for(int j = 0 ; j < m ; j += 1){
        auto i = all[j];
        if(find(i.second.first) != find(i.second.second)){
            maxi = j;
            par[find(i.second.first)] = find(i.second.second);
            if(i.first == -1){
                ans += 0;
            }else{
                ans += i.first;
            }
        }
    }
    if(all[maxi].first == -1){
        ans += mini;
    }
    cout << ans << endl;
}

int main(){
    int _;
    cin >> _;
    while(_--){
        solve();
    }
}
			   		  		 	  						 	 	 				