#include <bits/stdc++.h>
using namespace std;
long long power(long long x, long long y) {
  if (y == 0)
    return 1;
  else if (y % 2 == 0)
    return power(x, y / 2) * power(x, y / 2);
  else
    return x * power(x, y / 2) * power(x, y / 2);
}
const int N = 2e5 + 5;
vector<int> parent(N);
vector<int> s(N);
void make_set(int v) {
  parent[v] = v;
  s[v] = 1;
}
int find_set(int v) {
  if (v == parent[v]) {
    return v;
  }
  return parent[v] = find_set(parent[v]);
}
void union_sets(int a, int b) {
  a = find_set(a), b = find_set(b);
  if (a != b) {
    if (s[a] < s[b]) {
      int temp = a;
      a = b;
      b = temp;
    }
    parent[b] = a;
    s[a] += s[b];
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    int n, m, k;
    cin >> n >> m >> k;
    long long x[m], y[m], lim[m];
    int components = n;
    for (int i = 1; i <= n; i++) {
      make_set(i);
    }
    for (int i = 0; i < m; i++) {
      cin >> x[i] >> y[i] >> lim[i];
      if (lim[i] <= k and find_set(x[i]) != find_set(y[i])) {
        union_sets(x[i], y[i]);
        components--;
      }
    }
    sort(lim, lim + m);
    if (components > 1) {
      long long ans = 0;
      for (int i = 0; i < m; i++) {
        if (components > 1 and lim[i] > m and
            find_set(x[i]) != find_set(y[i])) {
          union_sets(x[i], y[i]);
          components--;
          ans += abs(lim[i] - k);
        }
      }
      cout << ans << '\n';
    } else {
      long long ans = (long long)1e9 + 7;
      for (int i = 0; i < m; i++) {
        ans = min(ans, abs(lim[i] - k));
      }
      cout << ans << '\n';
    }
    s.clear();
    parent.clear();
  }
  return 0;
}
