//多练，就是多练
#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
#include<cmath>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<cstring>
#include<unordered_map>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
//记得初始化和clear
//记得取模
//数组开够
//边界情况不要想当然
//特判记得return
int fa[300100];
struct Edge
{
	int from;//下一条边的编号 
	int to;//这条边到达的点 
	ll dis;//这条边的长度 
}edge[300100],me[300010];
bool cmp(Edge a,Edge b)
{
    return a.dis<b.dis;
}
int find(int v)
{
    if(fa[v] == v)
        return v;
    else
    {
        //路径压缩(使搜索祖宗的过程中，路径中搜索的结点的父亲的变为祖宗)
        fa[v] = find(fa[v]);
        return fa[v];
    }
}
void solve(int T)
{
    int n,m;
    ll k;
    cin>>n>>m>>k;
    int ecnt=0;
    ll mi=2e9;
    for(int i=1;i<=m;i++)
    {
        cin>>edge[i].from>>edge[i].to>>edge[i].dis;
        if(edge[i].dis<k)
        {
            ecnt++;
            me[ecnt].from=edge[i].from;
            me[ecnt].to=edge[i].to;
            me[ecnt].dis=abs(edge[i].dis-k);
        }
        if(edge[i].dis==k) {edge[i].dis=0;mi=min(mi,0ll);}
        else if(edge[i].dis>k) {mi=min(mi,abs(edge[i].dis-k));edge[i].dis=abs(edge[i].dis-k);}
        else edge[i].dis=0;
    }
    //cout<<mi<<endl;
    for(int i=1;i<=n;i++)
    {
        fa[i]=i;
    }
    int cnt=0; 
    ll ans1=2e9; 
    if(ecnt>=1)
    {
        sort(me+1,me+ecnt+1,cmp);
        for(int i=1;i<=ecnt;i++)    //对小边跑一遍生成树
        {
            //cout<<me[i].dis<<endl;
            int u=me[i].from;
            int v=me[i].to;
            if(u>v) swap(u,v);
            int fau=find(u);
            int fav=find(v);
            if(fau!=fav)
            {
                fa[fav]=fau;
                ans1=min(ans1,me[i].dis);
            }
    }
    for(int i=1;i<=n;i++)
    {
        find(i);
    }
    for(int i=1;i<=n;i++)
    {
        if(fa[i]==fa[1]) cnt++;
    }
    //cout<<"ans1: "<<ans1<<endl;
    //cout<<"cnt: "<<cnt<<endl;
    }
    if(cnt==n)
    {
        ans1=min(ans1,mi);
        cout<<ans1<<endl;
        return;
    }
    else
    {
        for(int i=1;i<=n;i++)
        {
            fa[i]=i;
        }
        ll ans=0;
        bool flag=0;
        sort(edge+1,edge+1+m,cmp);
        for(int i=1;i<=m;i++)
        {
            //cout<<ans<<endl;
            int u=edge[i].from;
            int v=edge[i].to;
            int fau=find(u);
            int fav=find(v);
            if(fau!=fav)
            {
                fa[fav]=fau;
                ans+=edge[i].dis;
				//cout<<edge[i].dis<<endl;
            }
        } 
        cout<<ans<<endl;
        return;
    }
}
//#define ONLINE_JUDGE
signed main()
{
    #ifndef ONLINE_JUDGE
    freopen("lotato.in","r",stdin);
    freopen("lotato.out","w",stdout);
    #endif
    int t=1;
    scanf("%d",&t);
    for(ll i=1;i<=t;i++)
    {
        solve(i);
    }
    return 0;
}