#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
const double Pi = acos(-1);
using namespace std;
int debug = 01;
int leader[200010];
int f(int n) {
  if (leader[n] == n) return n;
  return leader[n] = f(leader[n]);
}
void solve() {
  int n, m, k;
  cin >> n >> m >> k;
  int cnt[n + 10];
  vector<pair<int, pair<int, int>>> u, v;
  for (int i = 1; i <= n; i++) {
    cnt[i] = 1;
    leader[i] = i;
  }
  int ok = 0, op1 = 1000000010, op2 = 1000000010;
  while (m--) {
    int x, y, z;
    cin >> x >> y >> z;
    if (z == k) ok = 1;
    if (z <= k)
      v.push_back({z, {x, y}}), op1 = min(op1, k - z);
    else
      u.push_back({z, {x, y}}), op2 = min(op2, z - k);
  }
  sort(v.rbegin(), v.rend());
  sort(u.begin(), u.end());
  long long ans = 0;
  if (!ok && op2 < op1) {
    int x = u[0].second.first, y = u[0].second.second, z = u[0].first;
    if (x > y) swap(x, y);
    cnt[x] += cnt[y];
    cnt[y] = 0;
    leader[y] = x;
    ans = op2;
  }
  for (auto xx : v) {
    int x = xx.second.first, y = xx.second.second, z = xx.first;
    x = f(x), y = f(y);
    if (x == y) continue;
    if (x > y) swap(x, y);
    cnt[x] += cnt[y];
    cnt[y] = 0;
    leader[y] = x;
    if (cnt[1] == n) break;
  }
  if (!ok && op1 <= op2 && cnt[1] == n) {
    cout << k - v[0].first << "\n";
    return;
  }
  for (auto xx : u) {
    if (xx == *u.begin()) continue;
    int x = xx.second.first, y = xx.second.second, z = xx.first;
    x = f(x), y = f(y);
    if (x == y) continue;
    ans += (z - k);
    if (x > y) swap(x, y);
    cnt[x] += cnt[y];
    cnt[y] = 0;
    leader[y] = x;
    if (cnt[1] == n) break;
  }
  cout << ans << "\n";
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int tst = 1;
  cin >> tst;
  for (int T = 1; T <= tst; T++) {
    solve();
  }
}
