#include <bits/stdc++.h>
using namespace std;
int rnk[200005], par[200005];
void init(int n) {
  for (int i = 1; i <= n; i++) par[i] = i;
  for (int i = 1; i <= n; i++) rnk[i] = 0;
}
int Find(int r) {
  if (par[r] == r) return r;
  return par[r] = Find(par[r]);
}
void Union(int a, int b) {
  int u = Find(a);
  int v = Find(b);
  if (u == v) return;
  if (rnk[u] == rnk[v]) {
    par[u] = v;
    rnk[v]++;
  } else if (rnk[u] > rnk[v])
    par[v] = u;
  else if (rnk[u] < rnk[v])
    par[u] = v;
}
int MST(int node, vector<pair<long long, pair<long long, long long> > > v) {
  long long ret = 0;
  init(node);
  for (auto it : v) {
    int x = it.second.first, y = it.second.second, w = it.first;
    if (Find(x) == Find(y)) continue;
    Union(x, y);
    ret += w;
  }
  return ret;
}
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n, m, k;
    scanf("%d %d %d", &n, &m, &k);
    vector<pair<long long, pair<long long, long long> > > v;
    for (int i = 0; i < m; i++) {
      int x, y, w;
      scanf("%d %d %d", &x, &y, &w);
      v.push_back({w, {x, y}});
    }
    sort(v.begin(), v.end());
    vector<pair<long long, pair<long long, long long> > > tmp;
    for (auto it : v) {
      if (it.first <= k) tmp.push_back(it);
    }
    MST(n, tmp);
    int okay = 1;
    for (int i = 2; i <= n; i++) {
      if (Find(i) != Find(i - 1)) okay = 0;
    }
    long long ans1 = LLONG_MAX;
    if (okay) {
      for (auto it : v) {
        ans1 = min(ans1, abs(k - it.first));
      }
      printf("%lld\n", ans1);
      continue;
    }
    for (auto it : v) {
      it.first = max(0LL, it.first - k);
    }
    long long ans2 = MST(n, v);
    printf("%lld\n", ans2);
  }
}
