#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 5;
const int mod = 77797;
int fa[MAXN];
int cnt;
void init(int n) {
  cnt = 0;
  for (int i = 1; i <= n; i++) {
    fa[i] = i;
  }
}
int finder(int x) {
  if (fa[x] == x)
    return x;
  else
    return fa[x] = finder(fa[x]);
}
void combine(int u, int v) {
  int a = finder(u);
  int b = finder(v);
  fa[a] = b;
}
struct node {
  int u, v, w;
} e[MAXN];
void add(int u, int v, int w) {
  e[++cnt].u = u;
  e[cnt].v = v;
  e[cnt].w = w;
}
bool cmp(node a, node b) { return a.w < b.w; }
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n, m, k;
    scanf("%d%d%d", &n, &m, &k);
    init(n);
    int minn = 1e9;
    for (int i = 1; i <= m; i++) {
      int u, v, w;
      scanf("%d%d%d", &u, &v, &w);
      if (w <= k) {
        combine(u, v);
      } else {
        add(u, v, w - k);
      }
      minn = min(minn, abs(k - w));
    }
    sort(e + 1, e + 1 + cnt, cmp);
    int ans = 0;
    for (int i = 1; i <= cnt; i++) {
      if (finder(e[i].u) != finder(e[i].v)) {
        combine(e[i].u, e[i].v);
        ans += e[i].w;
      }
    }
    if (ans == 0) {
      cout << minn << endl;
    } else {
      cout << ans << endl;
    }
  }
}
