#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define ll          long long
#define p7          1000000007
#define p9          998244353
#define pb          push_back
#define ff          first
#define ss          second
#define vll         vector<ll>
#define pll         pair<ll,ll>
#define vpll        vector<pll>
#define mll         map<ll,ll>
#define test        ll T;cin>>T;while(T--)
#define ad(a,n)     vll a;a.resize(n);for(ll i=0;i<n;i++)cin>>a[i];
#define as(a,n)     for(ll i=0;i<n;i++){cout<<a[i]<<" ";}cout<<endl;
#define all(x)      x.begin(),x.end()

typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> pbds;

ll powm(ll x, ll y, ll m = p7) {
    x = x % m; ll res = 1; while (y)
    {if (y & 1)res = res * x; res %= m; y = y >> 1; x = x * x; x %= m;} return res;
}
ll modi(ll a, ll m = p7) {return powm(a, m - 2, m);}
void yesno(bool f) {f ? cout << "YES" << endl : cout << "NO" << endl;}


void ss99()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
}

ll par[200005];

ll get(ll x)
{
    if (x == par[x])
        return x;
    return (par[x] = get(par[x]));
}

ll unite(ll x, ll y)
{
    x = get(x);
    y = get(y);
    if (x != y)
    {
        par[x] = y;
        return true;
    }
    return false;
}


int32_t main()
{
    ss99();
    test
    {
        ll n, m, k; cin >> n >> m >> k;
        memset(par, 0, sizeof(ll) * (n + 5));
        vector<pair<ll, pll> > vp(m);
        for (ll i = 0; i < m; i++)
        {
            ll x, y, z; cin >> x >> y >> z;
            vp[i] = {z, {x - 1, y - 1}};
        }
        sort(all(vp));
        ll ans = 0;
        for (ll i = 0; i < m; i++)
        {
            ll x = vp[i].ss.ff;
            ll y = vp[i].ss.ss;
            ll z = vp[i].ff;
            if (unite(x, y))
                ans += max(z - k, 0ll);
        }
        if (ans == 0)
        {
            ans = 1e18;
            for (ll i = 0; i < m; i++)
            {
                ll z = vp[i].ff;
                ll cur = abs(z - k);
                ans = min(ans, cur);
            }
        }
        cout << ans << endl;
    }
    return 0;
}