#include <bits/stdc++.h>
using namespace std;
bool compare(tuple<long long int, long long int, long long int> t1,
             tuple<long long int, long long int, long long int> t2) {
  return get<2>(t1) < get<2>(t2) ? true : false;
}
long long int parent[200005];
long long int find(long long int node) {
  if (parent[node] == node) {
    return node;
  } else {
    return find(parent[node]);
  }
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    long long int n, m, k;
    cin >> n >> m >> k;
    vector<tuple<long long int, long long int, long long int>> v;
    map<pair<long long int, long long int>, long long int> p;
    long long int count = 0;
    long long int ans = 0, stillmin = LLONG_MAX, stillspeed = LLONG_MAX;
    for (long long int i = 1; i <= n; i++) {
      parent[i] = 0;
    }
    for (long long int i = 1; i <= m; i++) {
      long long int x, y, s;
      cin >> x >> y >> s;
      if (s <= k) {
        stillspeed = min(stillspeed, k - s);
      }
      if (s >= k) {
        stillmin = min(stillspeed, s - k);
      }
      v.push_back(make_tuple(x, y, max((long long int)0, s - k)));
    }
    sort(v.begin(), v.end(), compare);
    for (auto it : v) {
      long long int x, y, sp;
      x = get<0>(it), y = get<1>(it), sp = get<2>(it);
      long long int parentx = find(x);
      long long int parenty = find(y);
      if (parentx != parenty) {
        parent[x] = y;
        ans += sp;
      }
    }
    if (ans == 0) {
      ans = min(stillspeed, stillmin);
    }
    cout << ans << "\n";
  }
}
