#include <bits/stdc++.h>
using namespace std;
const long long int N = 300005;
const long long int mod = 1e9 + 7;
long long int n, i, j, m, k;
vector<long long int> g[N];
long long int color[N];
long long int par[N], sz[N], sum = 0;
vector<long long int> vp;
long long int getpar(long long int x) {
  if (par[x] == x) return x;
  return par[x] = getpar(par[x]);
}
bool merge(long long int x, long long int y) {
  long long int a = getpar(x);
  long long int b = getpar(y);
  if (a == b) return false;
  par[a] = b;
  return true;
}
vector<pair<long long int, pair<long long int, long long int>>> v1, v2;
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long int t;
  cin >> t;
  while (t--) {
    cin >> n >> m >> k;
    v1.clear();
    v2.clear();
    for (i = 1; i <= m; i++) {
      long long int x, y, z;
      cin >> x >> y >> z;
      if (z <= k)
        v1.push_back({z, {x, y}});
      else
        v2.push_back({z, {x, y}});
    }
    for (i = 1; i <= n; i++) {
      par[i] = i;
      sz[i] = 1;
    }
    sort(v1.begin(), v1.end());
    sort(v2.begin(), v2.end());
    long long int cnt = 0, ans = 1e9, c;
    for (auto x : v1) {
      if (merge(x.second.first, x.second.second)) {
        cnt++;
      }
    }
    if (cnt == n - 1) {
      ans = k - v1.back().first;
      if (!v2.empty()) {
        ans = min(ans, v2[0].first - k);
      }
    }
    long long int p = 0;
    for (auto x : v2) {
      if (cnt == n - 1) break;
      if (merge(x.second.first, x.second.second)) {
        cnt++;
        p += (x.first - k);
      }
      if (cnt == n - 1) ans = min(ans, p);
    }
    cout << ans << '\n';
  }
}
