
#include <bits/stdc++.h>
using namespace std;
#define f(i, n) for (i = 0; i <= n; i++)
#define F(i, k, n) for (i = k; k < n ? i <= n : i >= n; k < n ? i += 1 : i -= 1)
#define ll long long
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl
#define pb push_back
#define printarray(x, i, k)  \
    for (u = i; u <= k; u++) \
        cout << x[u] << " "; \
    printf("\n");
#define fast                          \
    ios_base::sync_with_stdio(false); \
    cin.tie(NULL);                    \
    cout.tie(NULL)
int i, j, u;

struct edge
{
    int x, y;
    ll w;
    bool operator<(edge const &other)
    {
        return w < other.w;
    }
};
int n;
ll m, k;
vector<edge> vec;
vector<int> par, depth;

int find_set(int a)
{
    //deb(a) ;
    if (par[a] == a)
        return a;

    return par[a] = find_set(par[a]);
}

void union_set(int x, int y)
{
    ///puts("well well well") ;
    int a = find_set(x);
    int b = find_set(y);

    if (depth[a] < depth[b])
        swap(a, b);

    par[b] = a;

    if (depth[a] == depth[b])
        depth[a]++;
}

void init()
{
    vec.clear();
    par.resize(n);
    depth.resize(n);

    for (int i = 0; i < n; i++)
    {
        par[i] = i;
        depth[i] = 0;
    }
}

void solve()
{

    cin >> n >> m >> k; //
    //deb2(n,m) ;
    // deb(k) ;
    vector<ll> weights;
    init();
    for (int i = 0; i < m; i++)
    {
        int x, y;
        ll w;
        cin >> x >> y >> w;
        x--;
        y--;
        edge a = {x, y, w};
        vec.push_back(a);
        weights.push_back(w);
    }

    sort(vec.begin(), vec.end());
    sort(weights.begin(), weights.end());

    vector<ll> change;
    ll max_weight = 0;
    for (edge &a : vec)
    {
        // puts("the start") ;
        // cout<<a.x<<" "<<a.y<<" "<<endl ;

        if (find_set(a.x) != find_set(a.y))
        {

           // cout << a.x << " " << a.y << " " << a.w << endl;
            //puts("hi") ;
            union_set(a.x, a.y);
            if (a.w > k)
            {
                change.push_back(a.w);
            }
            max_weight = max(max_weight, a.w);
        }
    }
    ll ans = 0;
    if (max_weight >= k)
    {
        for (ll x : change)
        {
            ans = ans + (x - k);
        }
    }
    else if (max_weight < k) //we are in trouble bois !
    {
        //ll temp = 100000000;
        int n = weights.size();
        if (weights[n - 1] < k)
        {
            //puts("dgd") ; 
            ans = abs(k - weights[n - 1]);
        }
        else
        {
           // puts("dfde") ; 
            auto it = lower_bound(weights.begin(), weights.end(), k) - weights.begin();
            int i = (int)it ; 
            ans = min ( abs(k-max_weight ) , abs(k-weights[i]) ) ;         
        }
    }

    cout << ans << endl;
}

int main()
{
    int t;
    cin >> t;
    while (t)
    {
        solve();
        t--;
    }

    return 0;
}