#include <bits/stdc++.h>
const long long INF = 0x3f3f3f3f3f3f3f3f;
const long long llinf = (1LL << 60);
const int inf = (1 << 30);
const int nmax = 2e5 + 50;
const long long mod = 1e9 + 7;
using namespace std;
int ts, n, m, k, i, x, y, z, p[nmax], sz[nmax];
long long sm, rs;
vector<pair<int, pair<int, int> > > a, b;
int fnd(int x) {
  if (p[x] == x) return x;
  return p[x] = fnd(p[x]);
}
void uni(int x, int y) {
  x = fnd(x), y = fnd(y);
  if (x == y) return;
  if (sz[x] < sz[y]) swap(x, y);
  p[y] = x;
  sz[x] += sz[y];
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cerr.tie(0);
  cout.tie(0);
  cin >> ts;
  while (ts--) {
    cin >> n >> m >> k;
    a.clear(), b.clear();
    for (i = 1; i <= m; i++) {
      cin >> x >> y >> z;
      if (z <= k)
        a.push_back(make_pair(z, make_pair(x, y)));
      else
        b.push_back(make_pair(z, make_pair(x, y)));
    }
    sort(a.begin(), a.end());
    sort(b.begin(), b.end());
    for (i = 1; i <= n; i++) {
      p[i] = i;
      sz[i] = 1;
    }
    for (i = (int)a.size() - 1; i >= 0; i--) {
      x = a[i].second.first, y = a[i].second.second;
      uni(x, y);
    }
    x = fnd(1);
    for (i = 2; i <= n; i++)
      if (x != fnd(i)) break;
    rs = llinf;
    if (i == n + 1) {
      rs = k - a.back().first;
      if (!b.empty()) rs = min(rs, 1LL * (b[0].first - k));
    } else {
      sm = 0;
      for (i = 0; i < (int)b.size(); i++) {
        x = b[i].second.first, y = b[i].second.second;
        if (fnd(x) != fnd(y)) {
          uni(x, y);
          sm += 1LL * b[i].first;
        }
      }
      rs = min(rs, sm);
    }
    cout << rs << '\n';
  }
  return 0;
}
