#include <bits/stdc++.h>
using namespace std;
vector<long long int> parent(2 * 100000 + 5);
vector<long long int> sizze(2 * 100000 + 5);
long long int findSet(long long int s) {
  if (s == parent[s]) {
    return s;
  } else {
    return parent[s] = findSet(parent[s]);
  }
}
void Union(long long int v1, long long int v2) {
  long long int s1 = findSet(v1);
  long long int s2 = findSet(v2);
  if (sizze[s1] <= sizze[s2]) {
    parent[v1] = parent[v2];
    sizze[s2] += sizze[s1];
  } else {
    parent[v2] = parent[v1];
    sizze[s1] += sizze[s2];
  }
}
long long int Kruskal(
    vector<pair<long long int, pair<long long int, long long int>>> edges) {
  long long int ans = 0;
  long long int k = edges.size();
  for (long long int i = 0; i < k; i++) {
    long long int v1 = edges[i].second.first;
    long long int v2 = edges[i].second.second;
    if (findSet(v1) != findSet(v2)) {
      Union(v1, v2);
      ans += edges[i].first;
    }
  }
  return ans;
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    long long int n, m, k;
    cin >> n >> m >> k;
    vector<pair<long long int, pair<long long int, long long int>>> edges;
    vector<long long int> edge;
    for (long long int i = 0; i < m; i++) {
      long long int x, y, s;
      cin >> x >> y >> s;
      edges.push_back({s, {x, y}});
    }
    sort((edges).begin(), (edges).end());
    for (long long int i = 0; i < m; i++) {
      edge.push_back(edges[i].first);
      if (edges[i].first < k) {
        edges[i].first = 0;
      } else {
        edges[i].first -= k;
      }
    }
    for (long long int i = 0; i < n + 1; i++) {
      parent[i] = i;
      sizze[i] = 1;
    }
    long long int ans = Kruskal(edges);
    if (ans != 0) {
      cout << ans << endl;
    } else {
      long long int ans = 1000000000;
      for (long long int i = 0; i < m; i++) {
        ans = min(ans, abs(edge[i] - k));
      }
      cout << ans << endl;
    }
  }
  return 0;
}
