#include <bits/stdc++.h>
using namespace std;
vector<int> parent;
void make_set(int v) { parent[v] = v; }
int find_set(int v) {
  return parent[v] = (parent[v] == v ? v : find_set(parent[v]));
}
bool connected(int a, int b) { return find_set(a) == find_set(b); }
bool union_set(int a, int b) {
  a = find_set(a);
  b = find_set(b);
  if (a != b) {
    if (b > a) swap(a, b);
    parent[b] = a;
    return true;
  }
  return false;
}
struct edge {
  int x, y, cost;
};
int main() {
  int t;
  cin >> t;
  for (int i = 0; i < t; i++) {
    int m, n, k, c = 0, min_ = 2e9;
    cin >> n >> m >> k;
    parent.assign(n, 0);
    vector<edge> edges;
    for (int j = 0; j < n; j++) make_set(j);
    for (int j = 0; j < m; j++) {
      edge e;
      cin >> e.x >> e.y >> e.cost;
      --e.x;
      --e.y;
      edges.push_back(e);
    }
    sort(edges.begin(), edges.end(),
         [](const edge& a, const edge& b) { return a.cost < b.cost; });
    for (auto e : edges) {
      if (connected(e.x, e.y)) {
        union_set(e.x, e.y);
        if (e.cost > k) c += e.cost - k;
      }
      min_ = min(min_, abs(e.cost - k));
    }
    if (c) {
      cout << c << endl;
    } else {
      cout << min_ << endl;
    }
  }
  return 0;
}
