#include<bits/stdc++.h>
#define inf 200000000000000000
#define eb emplace_back
#define pb push_back
#define fi first
#define se second
#define fastio ios::sync_with_stdio(false);cin.tie(NULL)
#define rng_23 mt19937 rng(chrono::steady_clock::now().time_since_epoch().count())
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pii;
typedef vector<ll> vi;
typedef vector<pair<ll,ll>> vii;
typedef set<ll> si;
typedef multiset<ll> msi;
typedef map<ll,ll> mii;
ll parent[200001];
class edge
{
public:
    ll x,y,l;
    edge(ll x,ll y,ll l): x(x),y(y),l(l) {}
};
bool comp1(edge &a,edge& b)
{
    return a.l<b.l;
}
bool comp2(edge &a,edge& b)
{
    return a.l>b.l;
}
ll rep(ll a)
{
    if(a==parent[a])
        return a;
    parent[a]=rep(parent[a]);
    return parent[a];
}
int main()
{
    fastio;
    ll t;
    cin>>t;
    while(t--){
    ll i,j,k;
    ll n,m,l;
    ll x,y;
    ll respos=inf,resneg=inf;
    vector<edge> edgeneg,edgepos;
    cin>>n>>m>>k;
    for(i=0;i<m;i++){
        cin>>x>>y>>l;
        if(l<=k)
            edgeneg.pb(edge(x,y,l-k));
        else
            edgepos.pb(edge(x,y,l-k));
    }
    sort(edgepos.begin(),edgepos.end(),comp1);
    sort(edgeneg.begin(),edgeneg.end(),comp2);
    for(i=1;i<=n;i++){
        parent[i]=i;
    }

    for(auto edge: edgeneg){
        //prllf("%d %d %d\n",edge.x,edge.y,edge.l);
        ll r1=rep(edge.x);
        ll r2=rep(edge.y);
        parent[r1]=r2;
        resneg=min(resneg,-edge.l);

    }
    si temp;
    for(i=1;i<=n;i++){
        temp.insert(rep(i));
    }

    if((ll)temp.size()>1ll)
        resneg=inf;
    else {
        if(!edgepos.empty()){
            resneg=min(resneg,edgepos.front().l);
        }
    }

    //printf("%d\n",resneg);

    if(!edgepos.empty()){
        respos=0;
    }
    //printf("%d\n",resn);
    for(auto edge: edgepos){
        //prllf("%d %d %d\n",edge.x,edge.y,edge.l);
        ll r1=rep(edge.x);
        ll r2=rep(edge.y);
        if(r1!=r2){
            parent[r1]=r2;
            respos+=edge.l;
        }
    }
    if(respos==0)
        respos=edgepos.front().l;
    cout<<min(respos,resneg)<<"\n";
    }
}
