#include <bits/stdc++.h>
using namespace std;
const long long mod = 235813;
const int MX = 100000;
int main() {
  cin.tie(0)->sync_with_stdio(0);
  int tc;
  cin >> tc;
  for (int n, m, k; tc--;) {
    cin >> n >> m >> k;
    vector<pair<int, pair<int, int> > > v(m);
    for (int i = 0; i < m; i++)
      cin >> v[i].second.first >> v[i].second.second >> v[i].first;
    sort(v.begin(), v.end());
    vector<int> par(n + 1);
    iota(par.begin(), par.end(), 0);
    function<int(int)> find = [&](int nw) {
      if (par[nw] == nw) return nw;
      return par[nw] = find(par[nw]);
    };
    function<void(pair<int, int>)> uni = [&](pair<int, int> nw) {
      int a = nw.first, b = nw.second;
      a = find(a), b = find(b);
      if (a != b) par[a] = b;
    };
    function<bool(pair<int, int>)> cc = [&](pair<int, int> nw) {
      return find(nw.first) == find(nw.second);
    };
    int min_diff = mod;
    pair<int, int> edge;
    for (int i = 0; i < m; i++) {
      if (abs(v[i].first - k) < min_diff) {
        min_diff = abs(v[i].first - k);
        edge = v[i].second;
      }
    }
    long long ans1 = min_diff;
    uni(edge);
    for (int i = 0; i < m; i++) {
      if (!cc(v[i].second)) {
        if (v[i].first > k) ans1 += v[i].first - k;
        uni(v[i].second);
      }
    }
    par.assign(n + 1, 0);
    iota(par.begin(), par.end(), 0);
    long long ans2 = 0;
    bool vv = 0;
    for (int i = 0; i < m; i++) {
      if (!cc(v[i].second)) {
        if (v[i].first > k) {
          ans2 += v[i].first - k;
          vv = 1;
        }
        uni(v[i].second);
      }
    }
    if (!vv) ans2 = mod * mod;
    cout << min(ans1, ans2) << "\n";
  }
}
