#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
#include <bits/stdc++.h>
#define owo(i,a, b) for(auto i=(a);i<(b); ++i)
#define uwu(i,a, b) for(auto i=(a)-1; i>=(b); --i)
#define senpai push_back
#define ttgl pair<int, int>
#define ayaya cout<<"ayaya~"<<endl
using namespace std;
/*#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ordered_set tree<ttgl, null_type,less<ttgl>, rb_tree_tag,tree_order_statistics_node_update>*/
 
using ll = long long;
using ld = long double;
const ll MOD = 1000000007;
const ll root = 62;
ll binpow(ll a,ll b){ll res=1;while(b){if(b&1)res=(res*a)%MOD;a=(a*a)%MOD;b>>=1;}return res;}
ll modInv(ll a){return binpow(a, MOD-2);}
const double PI = atan(1);
const double eps = 1e-10;
const int INF = 0x3f3f3f3f;
const int NINF = 0xc0c0c0c0;
const ll INFLL = 0x3f3f3f3f3f3f3f3f;
const ll NINFLL = 0xc0c0c0c0c0c0c0c0;
const int mxN = 200001;
int T;
int n, m, K;
pair<int, ttgl> edge[mxN];
vector<ttgl> adj[mxN];
int dsu[mxN];
int find(int a) {
    return a==dsu[a] ? a : dsu[a] = find(dsu[a]);
}
bool merge(int a, int b) {
    a = find(a);
    b = find(b);
    if(a==b)return false;
    dsu[a] = b;
    return true;
}
void solve() {
    cin>>n>>m>>K;
    iota(dsu, dsu+n, 0);
    int mx = 0;
    int mn = INF;
    owo(i, 0, m) {
        cin>>edge[i].second.first>>edge[i].second.second>>edge[i].first;
        edge[i].second.first--; edge[i].second.second--;
        if(edge[i].first <= K) {
            mx = max(mx, edge[i].first);
            merge(edge[i].second.first, edge[i].second.second);
        }else {
            mn = min(mn, edge[i].first);
        }
    }
    ll ans = INFLL;
    bool flag = 1;
    int val = find(0);
    owo(i, 1, n) {
        if(find(i)^val)flag = 0;
    }
    if(flag){
        if(mn!=INF) {
            ans = min(K - mx, mn - K);
        }else {
            ans = K - mx;
        }
    }
    if(!flag) {
        iota(dsu, dsu+n, 0);
        sort(edge, edge+m);
        ll res = 0;
        owo(i, 0, m) {
            if(merge(edge[i].second.first, edge[i].second.second)) {
                res += max(0, edge[i].first - K);
            }
        }
        ans = min(ans, res);
    }
    cout<<ans<<"\n";
}
int main() {
    //freopen("file.in", "r", stdin);
    //freopen("file.out", "w", stdout);
    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
    cin.tie(0)->sync_with_stdio(0);
    cin>>T;
    while(T--)solve();
    return 0;
}
