#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int x = 0, f = 1;
  char c = getchar();
  while (c != '-' && c < 48) c = getchar();
  if (c == '-') f = -1, c = getchar();
  while (c > 47) x = x * 10 + (c ^ 48), c = getchar();
  return f * x;
}
const int maxn = 3e5 + 7;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;
int n, m, k;
int fa[maxn];
int find(int a) { return fa[a] == a ? a : fa[a] = find(fa[a]); }
struct P {
  int u, v, w;
  bool operator<(const P &rhs) const { return w < rhs.w; }
} p[maxn];
void solve() {
  n = read(), m = read(), k = read();
  for (int i = 1; i <= m; ++i) {
    int u = read(), v = read(), w = read();
    p[i] = (P){u, v, w};
  }
  sort(p + 1, p + 1 + m);
  int pp = 0;
  for (int i = 1; i <= m; ++i)
    if (p[i].w <= k) pp = i;
  for (int i = 1; i <= n; ++i) fa[i] = i;
  for (int i = pp; i; --i) {
    auto [u, v, w] = p[i];
    int x = find(u), y = find(v);
    if (x != y) fa[x] = y;
  }
  int cnt = 0;
  for (int i = 1; i <= n; ++i) cnt += fa[i] == i;
  long long mians = 1e18;
  int f = 0, ff = 0;
  if (cnt == 1) mians = k - p[pp].w, f = 1;
  long long ans = 0;
  for (int i = pp + 1; i <= m; ++i) {
    auto [u, v, w] = p[i];
    int x = find(u), y = find(v);
    if (x != y)
      fa[x] = y, ans += w;
    else if (f && !ff)
      mians = min(mians, long long(w) - k), ff = 1;
  }
  printf("%lld\n", !f ? ans : mians);
}
int main() {
  int T = read();
  while (T--) solve();
}
