#include <bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
using li = long long int;
using ld = long double;
struct UnionFind {
  int n;
  vector<int> dad, size;
  UnionFind(int N) : n(N), dad(N), size(N, 1) {
    while (N--) dad[N] = N;
  }
  int root(int u) {
    if (dad[u] == u) return u;
    return dad[u] = root(dad[u]);
  }
  void join(int u, int v) {
    int Ru = root(u), Rv = root(v);
    if (Ru == Rv) return;
    if (size[Ru] > size[Rv]) swap(Ru, Rv);
    --n, dad[Ru] = Rv;
    size[Rv] += size[Ru];
  }
  bool areConnected(int u, int v) { return root(u) == root(v); }
  int getSize(int u) { return size[root(u)]; }
  int numberOfSets() { return n; }
};
vector<pair<int, pair<int, int> > > Wedges;
vector<pair<int, pair<int, int> > > mst;
UnionFind uf(0);
void init(int N) {
  mst.clear();
  Wedges.clear();
  uf = UnionFind(N);
}
void addEdge(int u, int v, int w) { Wedges.push_back({w, {u, v}}); }
int n, m, k;
int edgescnt = 0;
int cost = 0;
int kruskal() {
  sort(Wedges.begin(), Wedges.end());
  for (pair<int, pair<int, int> >& wedge : Wedges) {
    int u = wedge.second.first;
    int v = wedge.second.second;
    if (!uf.areConnected(u, v)) {
      uf.join(u, v);
      if (wedge.first <= k && edgescnt < n - 1) edgescnt++;
      if (wedge.first > k) {
        cost += wedge.first - k;
      }
    }
  }
  return cost;
}
void _main(int tc) {
  cin >> n >> m >> k;
  cost = 0;
  init(n);
  pair<int, pair<int, int> > must = {1 << 30, {-1, -1}};
  for (int i = 0; ((0 < m ? 1 : -1) < 0) ? i > m : i < m;
       i += (0 < m ? 1 : -1)) {
    int u, v, w;
    cin >> u >> v >> w;
    u--, v--;
    if (abs(k - w) < abs(must.first - k)) {
      must = {w, {u, v}};
    }
    addEdge(u, v, w);
  };
  ;
  ;
  edgescnt = 0;
  auto ans = kruskal();
  ;
  if (edgescnt == n - 1) {
    ;
    cout << abs(must.first - k) << '\n';
  } else {
    uf = UnionFind(n);
    cost = 0;
    cout << kruskal() << '\n';
  }
}
int main() {
  ios_base::sync_with_stdio(0), cin.tie(0);
  int tc;
  cin >> tc;
  for (int i = 0; ((0 < tc ? 1 : -1) < 0) ? i > tc : i < tc;
       i += (0 < tc ? 1 : -1))
    _main(i + 1);
}
