#include <bits/stdc++.h>
using namespace std;
template <typename T>
struct KRUSKAL {
  int n;
  KRUSKAL(int _n) : n(_n) {}
  struct edge {
    int u, v;
    T w;
    edge(int _u, int _v, T _w) : u(_u), v(_v), w(_w) {}
    const bool operator<(const edge &other) const { return w < other.w; }
  };
  vector<edge> e;
  struct DSU {
    int n;
    vector<int> par, rnk;
    DSU(int _n) {
      n = _n + 5;
      par.resize(n);
      rnk.resize(n);
      for (int i = 1; i < n; ++i) par[i] = i;
    }
    int find_set(int a) {
      return (a == par[a] ? a : par[a] = find_set(par[a]));
    }
    void union_set(int a, int b) {
      a = find_set(a);
      b = find_set(b);
      if (a != b) {
        if (rnk[a] < rnk[b]) swap(a, b);
        par[b] = a;
        if (rnk[a] == rnk[b]) ++rnk[a];
      }
    }
  };
  void addEdge(int u, int v, T w) { e.push_back({u, v, w}); }
  pair<T, T> MST(int k) {
    T mx = 0;
    T ans = 0;
    sort(e.begin(), e.end());
    DSU D(n + 5);
    for (auto i : e) {
      if (D.find_set(i.u) != D.find_set(i.v)) {
        mx = max(mx, i.w);
        if (i.w > k) ans += i.w - k;
        D.union_set(i.u, i.v);
      }
    }
    return make_pair(mx, ans);
  }
};
signed main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int TT;
  cin >> TT;
  while (TT--) {
    vector<int> V;
    int n, m, k;
    cin >> n >> m >> k;
    KRUSKAL<int> mst(n);
    for (int i = 0; i < m; ++i) {
      int u, v, w;
      cin >> u >> v >> w;
      mst.addEdge(u, v, w);
      V.push_back(w);
    }
    sort(V.begin(), V.end());
    pair<long long, long long> p = mst.MST(k);
    if (p.first >= k)
      cout << p.second << '\n';
    else {
      int ans = 1e9;
      for (auto i : V) ans = min(ans, abs(k - i));
      cout << ans << '\n';
    }
  }
  return 0;
}
