#include <bits/stdc++.h>
using namespace std;
template <class T>
T mceil(T a, T b) {
  if (a % b == 0)
    return a / b;
  else
    return a / b + 1;
}
class union_find {
 public:
  vector<long long int> par;
  int n;
  int no_of_components = n;
  vector<long long int> siz;

 public:
  union_find(int nv) {
    n = nv;
    no_of_components = n;
    par.resize(n + 1);
    siz.resize(n + 1);
    for (int i = 1; i <= n; i++) {
      par[i] = i;
      siz[i] = 1;
    }
  }
  int get_root(int i) {
    if (i == par[i]) return i;
    return par[i] = get_root(par[i]);
  }
  int take_union(int a, int b) {
    int u = get_root(a);
    int v = get_root(b);
    if (u == v) {
      return no_of_components;
    }
    if (siz[v] > siz[u]) swap(u, v);
    par[v] = u;
    siz[u] += siz[v];
    siz[v] = 1;
    return no_of_components--;
  }
  bool find(int a, int b) { return get_root(a) == get_root(b); }
};
struct ed {
  long long int a, b, w;
};
bool comp(ed a, ed b) {
  if (a.w <= b.w) return true;
  return 0;
}
void solve() {
  long long int n, m, k;
  cin >> n >> m >> k;
  vector<ed> v(m);
  long long int mn = INT_MAX, mx = INT_MIN;
  long long int ind = -1;
  for (long long int i = 0; i < m; i++) {
    cin >> v[i].a >> v[i].b >> v[i].w;
    if (mn > abs(k - v[i].w)) {
      mn = abs(k - v[i].w);
      ind = i;
    }
    mx = max(mx, v[i].w);
  }
  if (mx <= k) {
    cout << k - mx << "\n";
    return;
  }
  union_find dsu(n + 1);
  dsu.take_union(v[ind].a, v[ind].b);
  sort((v).begin(), (v).end(), comp);
  for (long long int i = 0; i < m; i++) {
    if (!dsu.find(v[i].a, v[i].b)) {
      dsu.take_union(v[i].a, v[i].b);
      if (v[i].w > k) mn += v[i].w - k;
    }
  }
  cout << mn << "\n";
}
int main() {
  ios_base ::sync_with_stdio(false);
  cin.tie(NULL);
  long long int t;
  cin >> t;
  while (t--) {
    solve();
  }
}
