#include <bits/stdc++.h>
using namespace std;
int cases = 1;
struct info {
  int u, v;
  long long w;
};
vector<info> graph;
int par[200005], cnt, rnk[200005];
bool cmp(const info& a, const info& b) {
  if (a.w < b.w) return true;
  return false;
}
int find_set(int v) {
  if (v == par[v]) return v;
  return par[v] = find_set(par[v]);
}
void mrg(int a, int b) {
  if (rnk[a] <= rnk[b]) {
    par[a] = b;
    rnk[b]++;
  } else {
    par[b] = a;
    rnk[a]++;
  }
}
int MST(int n) {
  long long sum = 0;
  for (int i = 0; i < graph.size(); i++) {
    int a = find_set(graph[i].u);
    int b = find_set(graph[i].v);
    if (a != b) {
      mrg(a, b);
      cnt++;
      sum += graph[i].w;
    }
    if (cnt == n - 1) break;
  }
  return sum;
}
bool tree(int n) {
  for (int i = 1; i < n; i++) {
    if (find_set(i) != find_set(i + 1)) return false;
  }
  return true;
}
void CLR(int n) {
  graph.clear();
  cnt = 0;
  for (int i = 1; i <= n; i++) par[i] = 0, rnk[i] = 0;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    long long k, mini = LLONG_MAX;
    cin >> n >> m >> k;
    vector<pair<long long, pair<int, int>>> kom, shb;
    for (int i = 0; i < m; i++) {
      int u, v;
      long long w;
      cin >> u >> v >> w;
      info temp;
      temp.u = u;
      temp.v = v;
      temp.w = w;
      if (w <= k) graph.push_back(temp);
      shb.push_back({w, {u, v}});
    }
    sort(shb.begin(), shb.end());
    sort(graph.begin(), graph.end(), cmp);
    for (int i = 1; i <= n; i++) par[i] = i;
    MST(n);
    if (tree(n)) {
      long long ans = LLONG_MAX;
      for (auto it : shb) ans = min(ans, abs(it.first - k));
      cout << ans << "\n";
    } else {
      for (int i = 1; i <= n; i++) par[i] = i;
      for (int i = 0; i < graph.size(); i++) graph[i].w = 0;
      cnt = 0;
      for (auto it : shb) {
        if (it.first > k) {
          info temp;
          temp.u = it.second.first;
          temp.v = it.second.second;
          temp.w = it.first - k;
          graph.push_back(temp);
        }
      }
      sort(graph.begin(), graph.end(), cmp);
      cout << MST(n) << "\n";
    }
    CLR(n + 2);
  }
}
