#include <bits/stdc++.h>
 
#define all(x) (x).begin(), (x).end()
#define size(x) (int)((x).size())
 
using namespace std;
 
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
 
mt19937 eng(chrono::steady_clock::now().time_since_epoch().count());
 
const int N = 2e5 + 4;

struct edge{
    int u, v, s;
    edge() : u(0), v(0), s(0) {}
    edge(int u_, int v_, int s_) :
        u(u_), v(v_), s(s_) {}
};

int n, m, k;
vector<pii> g[N];
vector<edge> e;
int sz[N], rep[N];
bool used[N];

void init(int u){
    sz[u] = 1;
    rep[u] = u;
}

int findRep(int u){
    if (rep[u] == u) return u;
    return rep[u] = findRep(rep[u]);
}

void uniSets(int u, int v){
    u = findRep(u);
    v = findRep(v);
    if (u == v) return;

    if (sz[u] < sz[v]) swap(u, v);
    sz[u] += sz[v];
    rep[v] = u;
}

bool cmp(edge& u, edge& v){
    if (abs(u.s - k) != abs(v.s - k)){
        return abs(u.s - k) < abs(v.s - k);
    }
    if (u.u != v.u) return u.u < v.u;
    return u.v < v.v;
}

void clear(){
    e.clear();
    for (int i = 1; i <= n; ++i){
        g[i].clear();
        init(i);
        used[i] = false;
    }
}

void read(){
    cin >> n >> m >> k;
    clear();
    for (int i = 0; i < m; ++i){
        int u, v, s;
        cin >> u >> v >> s;
        e.emplace_back(u, v, s);
        g[u].emplace_back(v, s);
        g[v].emplace_back(u, s);
    }
}

void dfs(int u, int par){
    used[u] = true;
    uniSets(u, par);
    for (pii to : g[u]){
        if (used[to.first] || to.second > k) continue;
        dfs(to.first, par);
    }
}

void solve() {
    read();
    int cnt = 0;
    for (int i = 1; i <= n; ++i){
        if (used[i]) continue;
        dfs(i, i);
        ++cnt;
    }

    if (cnt == 1){
        int mn = 1e9;
        for (edge& ed : e){
            mn = min(mn, abs(ed.s - k));
        }
        cout << mn << "\n";
        return;
    }

    sort(all(e), cmp);
    ll ans = 0;
    for (edge& ed : e){
        int u = findRep(ed.u);
        int v = findRep(ed.v);
        if (u == v) continue;
        uniSets(u, v);
        ans += abs(ed.s - k);
    }
    cout << ans << "\n";
}
 
int main() {
    ios::sync_with_stdio(0);
    cout.tie(0), cin.tie(0);
 
    int z = 1;
    cin >> z;
    while (z--) {
        solve();
    }
 
    return 0;
}