#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
template <typename... T>
void rd(T&... args) {
  ((cin >> args), ...);
}
template <typename... T>
void wr(T... args) {
  ((cout << args << " "), ...);
  cout << endl;
}
struct UF {
  vector<int> fa, size;
  UF(int n) : fa(n), size(n, 1) { iota((fa).begin(), (fa).end(), 0); }
  int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); }
  bool connected() { return size[find(0)] == fa.size(); }
  bool join(int x, int y) {
    x = find(x), y = find(y);
    if (x == y) return true;
    if (size[x] > size[y]) swap(x, y);
    fa[x] = y;
    size[y] += size[x];
    return false;
  }
};
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int tt;
  cin >> tt;
  while (tt--) {
    int n, m, k;
    cin >> n >> m >> k;
    vector<tuple<int, int, int>> edges(m);
    for (auto& [c, x, y] : edges) {
      cin >> x >> y >> c;
      x--, y--;
    }
    sort((edges).begin(), (edges).end());
    UF uf(n);
    ll ans = 1e18;
    ll extra = 0;
    bool is_first = 0;
    for (const auto& [c, x, y] : edges) {
      if (!is_first && c > k) {
        if (uf.connected()) ans = min<ll>(ans, c - k);
        is_first = 1;
      } else if (c > k && !uf.connected()) {
        if (!uf.join(x, y)) {
          extra += c - k;
        }
        if (uf.connected()) ans = min(ans, extra);
      } else if (c <= k) {
        uf.join(x, y);
        if (uf.connected()) ans = min<ll>(ans, k - c);
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
