#include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long> > v[200001];
long long p[200001];
long long Root(long long x) {
  while (x != p[x]) {
    p[x] = p[p[x]];
    x = p[x];
  }
  return x;
}
signed main() {
  long long t;
  cin >> t;
  while (t--) {
    long long n, m, k;
    cin >> n >> m >> k;
    for (long long i = 1; i <= n; i++) p[i] = i;
    vector<pair<long long, pair<long long, long long> > > edgesp, edgesn;
    for (long long i = 0; i < m; i++) {
      long long x, y, w;
      cin >> x >> y >> w;
      if (w >= k)
        edgesp.push_back({w, {x, y}});
      else
        edgesn.push_back({w, {x, y}});
    }
    sort(edgesp.begin(), edgesp.end());
    sort(edgesn.begin(), edgesn.end(),
         greater<pair<long long, pair<long long, long long> > >());
    long long ans = 1e9 + 7;
    long long cnt = 0;
    for (long long i = 0; i < (long long)edgesn.size(); i++) {
      long long x = edgesn[i].second.first, y = edgesn[i].second.second;
      if (Root(x) != Root(y)) {
        cnt++;
        p[Root(x)] = Root(y);
      }
    }
    if (cnt == n - 1) {
      for (long long i = 0; i < (long long)edgesp.size(); i++) {
        ans = min(ans, edgesp[i].first - k);
      }
      for (long long i = 0; i < (long long)edgesn.size(); i++) {
        ans = min(ans, k - edgesn[i].first);
      }
      cout << ans << "\n";
      continue;
    }
    long long cost = 0;
    for (long long i = 0; i < (long long)edgesp.size(); i++) {
      long long x = edgesp[i].second.first, y = edgesp[i].second.second;
      if (Root(x) != Root(y)) {
        p[Root(x)] = Root(y);
        cost += edgesp[i].first - k;
      }
    }
    ans = min(cost, ans);
    cout << ans << "\n";
  }
}
