#include <bits/stdc++.h>
using namespace std;
void solve();
long long int power(long long int n, long long int k,
                    long long int m = 1000000007) {
  if (k == 0) return 1;
  if (k % 2) return (n * power(n, k - 1, m)) % m;
  return power((n * n) % m, k / 2, m);
}
long long int gcd(long long int a, long long int b) {
  return b ? gcd(b, a % b) : a;
}
long long int lcm(long long int a, long long int b) {
  return (((a * b) % 1000000007) * power((gcd(a, b)), 1000000007 - 2)) %
         1000000007;
}
int main() {
  ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
  solve();
  return 0;
}
class priorityQueueCondition {
 public:
  bool operator()(vector<long long int> const &vec1,
                  vector<long long int> const &vec2) {
    return vec1[2] > vec2[2];
  }
};
struct node {
  node *parent = NULL;
};
node *find(node *x) {
  if (x->parent == x) {
    return x;
  } else {
    return find(x->parent);
  }
}
void solve() {
  long long int t;
  cin >> t;
  while (t--) {
    long long int n, m, k;
    cin >> n >> m >> k;
    vector<node> graph(n + 1);
    for (int i = 0; i <= n; i++) {
      graph[i].parent = &graph[i];
    }
    priority_queue<vector<long long int>, vector<vector<long long int>>,
                   priorityQueueCondition>
        pq;
    for (int i = 0; i < m; i++) {
      long long int a, b, w;
      cin >> a >> b >> w;
      pq.push({a, b, w});
    }
    long long int counter = 0;
    long long int cost = 0;
    long long int maxw = 0;
    while (counter != n - 1) {
      long long int a = pq.top()[0], b = pq.top()[1], w = pq.top()[2];
      pq.pop();
      node *A = find(&graph[a]);
      node *B = find(&graph[b]);
      if (A != B) {
        graph[a].parent = &graph[b];
        counter++;
        if (w > k) {
          cost += w - k;
        }
        maxw = max(maxw, w);
      }
    }
    if (maxw >= k) {
      cout << cost << "\n";
    } else {
      cost = INT_MAX;
      while (!pq.empty()) {
        cost = min(cost, abs(pq.top()[2] - k));
        pq.pop();
      }
      cout << cost << "\n";
    }
  }
}
