#include <bits/stdc++.h>
using namespace std;
vector<bool> prime(200002, true);
void seive(long long mx) {
  prime[0] = prime[1] = false;
  for (long long i = 2; i * i <= mx; i++) {
    if (prime[i]) {
      for (long long j = i * i; j <= mx; j += i) {
        prime[j] = false;
      }
    }
  }
}
const long long M = 1e9 + 7;
const long long Mxn = 3e5;
long long power(long long i, long long p) {
  long long ans = 1;
  while (p) {
    if (p & 1) ans = (ans * i) % M;
    i = (i * i) % M;
    p /= 2;
  }
  return ans % M;
}
long long find_parent(long long node, vector<long long> &par) {
  if (par[node] == node)
    return node;
  else
    return par[node] = find_parent(par[node], par);
}
void Union(long long x, long long y, vector<long long> &par) {
  par[par[x]] = par[y];
}
int main() {
  int t = 1;
  cin >> t;
  while (t--) {
    long long n, m, k, cost = 0;
    cin >> n >> m >> k;
    vector<vector<long long>> arr, ans;
    for (long long i = 0; i < m; i++) {
      long long x, y, w;
      cin >> x >> y >> w;
      x--;
      y--;
      arr.push_back({w, x, y});
    }
    vector<long long> par(n);
    for (long long i = 0; i < n; i++) par[i] = i;
    sort(arr.begin(), arr.end());
    long long l = 0, idx = 0;
    for (long long i = 0; i < m; i++) {
      if (l == n - 2 && arr[i][0] < k) {
        idx = i;
        break;
      }
      if (l == n - 1) break;
      if (find_parent(arr[i][1], par) != find_parent(arr[i][2], par)) {
        ans.push_back(arr[i]);
        Union(find_parent(arr[i][1], par), find_parent(arr[i][2], par), par);
        l++;
      } else {
        continue;
      }
    }
    if (l == n - 2) {
      vector<long long> mincost = {0, 0, 0};
      for (long long i = idx; i < m; i++) {
        if (find_parent(arr[i][1], par) != find_parent(arr[i][2], par)) {
          if (abs(mincost[0] - k) > abs(arr[i][0] - k)) mincost = arr[i];
        }
      }
      ans.push_back(mincost);
    }
    for (long long i = 0; i < ans.size(); i++) {
      if (ans[i][0] > k) cost += abs(ans[i][0] - k);
    }
    if (cost == 0) {
      cost += abs(ans.back()[0] - k);
    }
    cout << cost << endl;
  }
  return 0;
}
