#include <bits/stdc++.h>
using namespace std;
const long long inf = 1100000000000000000;
long long par[1000100], sz[1000100];
long long n, m, k;
long long fin(long long x) {
  if (par[x] == x) return x;
  return (par[x] = fin(par[x]));
}
void uni(long long x, long long y) {
  long long px = fin(x);
  long long py = fin(y);
  if (px != py) {
    if (sz[px] > sz[py]) swap(px, py);
    par[px] = py;
    sz[py] += sz[px];
  }
}
void solve() {
  cin >> n >> m >> k;
  fill(sz, sz + n + 1, 1);
  for (long long i = 1; i <= n; i++) par[i] = i;
  vector<pair<long long, pair<long long, long long> > > v;
  long long mn = inf;
  pair<long long, long long> id;
  for (long long i = 0; i < m; i++) {
    long long x, y, s;
    cin >> x >> y >> s;
    v.push_back({s, {x, y}});
  }
  long long ans = 0, cnt = 1;
  sort(v.begin(), v.end());
  for (long long i = 0; i < m; i++) {
    long long x = v[i].second.first, y = v[i].second.second;
    if (fin(x) != fin(y) && cnt < n - 1) {
      ans += max(0ll, v[i].first - k);
      uni(x, y);
      ++cnt;
    } else {
      if (ans) {
        ans += max(0ll, v[i].first - k);
        break;
      } else {
        mn = min(mn, abs(v[i].first - k));
      }
    }
  }
  if (!ans) ans = mn;
  cout << ans;
}
signed main() {
  ios_base::sync_with_stdio(false), cin.tie(nullptr);
  long long T = 1;
  cin >> T;
  while (T--) {
    solve();
    cout << '\n';
  }
  return 0;
}
