#include <bits/stdc++.h>
using namespace std;
const long long N = 2e5 + 5;
long long findParent(long long p, vector<long long> &parent) {
  if (parent[p] == p) return p;
  return parent[p] = findParent(parent[p], parent);
}
void solve() {
  long long n, m, k;
  cin >> n >> m >> k;
  vector<vector<long long> > ed, vec;
  long long mn = 1e15, idx = -1;
  for (long long i = 0; i < m; i++) {
    long long a, b, w;
    cin >> a >> b >> w;
    ed.push_back({w, a, b});
    if (abs(w - k) < mn) {
      mn = abs(w - k);
      idx = i;
    }
  }
  ed[idx][0] = 1e15;
  long long ans = mn;
  vector<long long> parent(n + 1);
  for (long long i = 0; i < n + 1; i++) parent[i] = i;
  sort(ed.begin(), ed.end());
  long long i = 0;
  while ((long long)(vec.size()) < n - 2) {
    vector<long long> cur = ed[i];
    long long a = findParent(cur[1], parent);
    long long b = findParent(cur[2], parent);
    if (a != b) {
      vec.push_back(cur);
      parent[a] = b;
      if (cur[0] > k) {
        ans += (cur[0] - k);
      }
    }
    i++;
  }
  cout << ans << "\n";
}
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
