#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
const int INF = 0x3f3f3f3f;
int n, m, k;
vector<int> g[N], G[N];
int u[N], v[N], w[N], f[N];
int vis[N];
struct EDGE {
  int u, v, w;
  bool operator<(const EDGE &i) const { return w < i.w; }
} e[N << 1];
int tot = 0;
void add_edge(int u, int v, int w) {
  e[tot].u = u, e[tot].v = v, e[tot++].w = w;
}
void dfs(int u, int fa) {
  vis[u] = 1;
  for (auto x : G[u]) {
    if (x == fa || vis[x]) continue;
    dfs(x, u);
  }
}
int check() {
  int sz = 0;
  for (int i = 1; i <= n; i++) {
    if (!vis[i]) {
      dfs(i, -1);
      sz++;
    }
  }
  if (sz == 1) return 1;
  return 0;
}
int find(int x) {
  if (x != f[x]) f[x] = find(f[x]);
  return f[x];
}
int kruskal() {
  int tmp = 0, sz = 0;
  sort(e, e + tot);
  for (int i = 0; i < tot; i++) {
    int a = find(e[i].u);
    int b = find(e[i].v);
    if (a != b) {
      a = f[b];
      sz++;
      tmp += e[i].w;
    }
    if (sz == n - 1) return tmp;
  }
}
int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    scanf("%d%d%d", &n, &m, &k);
    for (int i = 0; i < N; i++) {
      G[i].clear();
      f[i] = i;
      vis[i] = false;
    }
    int ans = INF;
    for (int i = 1; i <= m; i++) {
      scanf("%d%d%d", &u[i], &v[i], &w[i]);
      ans = min(ans, abs(k - w[i]));
      if (w[i] <= k) {
        G[u[i]].push_back(v[i]);
        G[v[i]].push_back(u[i]);
      }
    }
    int tag = check();
    if (tag) {
      printf("%d\n", ans);
      continue;
    }
    tot = 0;
    for (int i = 1; i <= m; i++) {
      int tmp = max(0, w[i] - k);
      add_edge(u[i], v[i], tmp);
      add_edge(v[i], u[i], tmp);
    }
    ans = kruskal();
    printf("%d\n", ans);
  }
  return 0;
}
