#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
#include <map>
#include <set>
#include <unordered_map>
#include <numeric>
#include <iomanip>
#include <queue>
using namespace std;
#define int long long
#define all(v) v.begin(), v.end()
#define F first
#define S second

const int mod = 1e9 + 7;
const int N = 1e6 + 5;

vector<int> sz;
vector<int> p;

void init(int n) {
    sz.clear();
    p.clear();
    sz.resize(n);
    p.resize(n);
}

void make_set(int v) {
    p[v] = v;
    sz[v] = 1;
}

int get(int v) {
    if (p[v] == v)
        return v;
    return p[v] = get(p[v]);
}

void merge(int a, int b) {
    a = get(a);
    b = get(b);
    if (sz[a] > sz[b]) 
        swap(a, b);
    sz[b] += sz[a];
    p[a] = b;
}

struct EDGE {
    int v, u, w;
};


signed main() {
    cin.tie(0);
    cout.tie(0);
    ios_base::sync_with_stdio(0);
    int t;
    cin >> t;
    while (t--) {
        int n, m, k;
        cin >> n >> m >> k;
        init(n);
        for (int i = 0; i < n; ++i) {
            make_set(i);
        }
        vector<EDGE> edge(m);
        for (auto& [v, u, w] : edge) {
            cin >> v >> u >> w;
            --v, --u;
        }
        int j = 0;
        int comps = n;
        for (int i = 0; i < m; ++i) {
            if (abs(edge[i].w - k) < abs(edge[j].w - k)) {
                j = i;
            }
        }
        merge(edge[j].u, edge[j].v);
        comps--;
        int cur_res = abs(edge[j].w - k);
        int sum = max(edge[j].w - k, 0LL);
        for (int i = 0; i < m; ++i) {
            if (edge[i].w <= k) {
                if (get(edge[i].v) != get(edge[i].u)) {
                    merge(edge[i].v, edge[i].u);
                    comps--;
                }
            }
        }
        sort(all(edge), [&](auto& x, auto& y) {
            return x.w < y.w;
        });
        for (int i = 0; i < m; ++i) {
            if (get(edge[i].v) != get(edge[i].u)) {
                merge(edge[i].v, edge[i].u);
                comps--;
                sum += edge[i].w - k;
            }
        }
        cout << max(sum, cur_res) << '\n';
    }
    return 0;
}
