/**
 * Author: ngkan
 * ┬┴┬┴┤(･_├┬┴┬┴ hiding from those WAs
 */

#include <bits/stdc++.h>
using namespace std;

const int N = (int) 1e5 + 5;
const int mod = (int) 1e9 + 7;
const double EPS = 1e-9;

mt19937 rng(std::chrono::system_clock::now().time_since_epoch().count());

/******************************************************************************/

struct DSU{
    vector <int> p, sz;
    DSU(int n = 0): p(n+1), sz(n+1, 1)  { for(int i=0;i<=n;i++) p[i] = i;}
    int find(int x)     { return x == p[x] ? x : p[x] = find(p[x]); }
    int get_size(int x) { return sz[find(x)]; }
    void merge(int x,int y){   
        if ((x = find(x)) == (y = find(y))) return;
        if (sz[x] < sz[y])  swap(x, y);
        sz[x] += sz[y];
        p[y] = x;
    }
};

void ngk(){
    int n, m, k;
    vector <pair<int, pair<int,int>>> edges;

    cin >> n >> m >> k;
    DSU dsu(n);

    for(int i=1;i<=m;i++){
        int x, y, w;
        cin >> x >> y >> w;
        edges.push_back({w, {x, y}});
    }

    long long ans = 0;

    sort(edges.begin(), edges.end());
    bool big = false;
    int close = (int) 2e9;

    for(auto e: edges){
        int w = e.first;
        int x, y;
        tie(x, y) = e.second;
        
        close = min(close, abs(w-k));

        if (dsu.find(x) == dsu.find(y))
            continue;
        
        if (w > k)
            big = true;

        ans += max(0, w - k);
        dsu.merge(x, y);
    }
    
    if (big)
        cout << ans << '\n';
    else
        cout << close << '\n';
}

int main(int argc, char *argv[]){
    iostream::sync_with_stdio(0);
    int test = 1;
    cin >> test;
    while(test--){
        ngk();
    }
    return 0;
}
