#include <bits/stdc++.h>
#define int long long
#define ff first
#define ss second
#define ll long long
#define ld long double
#define pb push_back
#define eb emplace_back
#define pii pair<int, int>
#define pll pair<ll, ll>
#define ti tuple<int, int, int>
#define vi vector<int>
#define vl vector<ll>
#define vii vector<pii>
#define sws ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define endl '\n'
#define teto(a, b) (((a)+(b)-1)/(b))
#define all(x) x.begin(), x.end()
#define forn(i, n) for(int i = 0; i < (int)n; i++)
#define forne(i, a, b) for(int i = a; i <= b; i++)
#define dbg(msg, var) cerr << msg << " " << var << endl;

using namespace std;

const int MAX = 9*1e6+10;
const ll MOD = 1e9+7;
const int INF = 0x3f3f3f3f;
const ll LLINF = 0x3f3f3f3f3f3f3f3f;
const ld EPS = 1e-9;
const ld PI = acos(-1);

// End Template //

struct DSU {
    int n;
    vi parent, size;

    DSU(int n) {
        this->n = n;
        parent.assign(n+1, 0);
        size.assign(n+1, 1);

        for(int i=0;i<=n;i++)
            parent[i] = i;
    }

    int find(int v) {
        if(v==parent[v])
            return v;
        return parent[v]=find(parent[v]);
    }

    void join(int a, int b) {
        a = find(a);
        b = find(b);
        if(a!=b) {
            if(size[a]<size[b])
                swap(a, b);

            parent[b]=a;
            size[a]+=size[b];
        }
    }
};


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

int32_t main()
{sws;

    int t;
    cin >> t;
    while(t--){
        int n, m, k, u, v, w;
        cin >> n >> m >> k;
        DSU dsu(n);
        vector<Edge> edges, result;
        int cost = 0;

        for(int i=0;i<m;i++){
            cin >> u >> v >> w;
            edges.pb((Edge){u, v, w});
        }

        sort(edges.begin(), edges.end());

        for(auto e : edges) {
            if (dsu.find(e.u) != dsu.find(e.v)) {
                cost += e.weight;
                result.push_back(e); // vector com as arestas da MST
                dsu.join(e.u, e.v);
            }
        }

        int m1 = 0;
        for(auto r: result){
            m1 = max(m1, r.weight);
        }

        if(m1>=k){
            cout << m1-k << endl;
        }else{
            int m2 = 0;
            for(auto e: edges){
                if(abs(m2-k)>abs(e.weight-k))
                    m2 = e.weight;
            }
            cout << abs(m2-k) << endl;
        }

    }
    

    return 0;

}