#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
const int inf = 0x3f3f3f3f;
struct node {
  int u, v, w;
  bool operator<(const node b) const { return w < b.w; }
};
bool cmp(node a, node b) { return a.w > b.w; }
int fa[N];
int Find(int x) {
  if (x == fa[x]) return x;
  return fa[x] = Find(fa[x]);
}
node edge[N];
int main() {
  int t, n, m, k;
  scanf("%d", &t);
  while (t--) {
    long long ans = inf, res = 0;
    scanf("%d%d%d", &n, &m, &k);
    for (int i = 1; i <= m; i++)
      scanf("%d%d%d", &edge[i].u, &edge[i].v, &edge[i].w);
    for (int i = 1; i <= n; i++) fa[i] = i;
    sort(edge + 1, edge + 1 + m);
    int p = m + 1;
    for (int i = 1; i <= m; i++) {
      if (edge[i].w > k) {
        p = i;
        break;
      }
    }
    sort(edge + 1, edge + p, cmp);
    int cnt = 0, f = 0;
    for (int i = 1; i <= m; i++) {
      int fx = Find(edge[i].u), fy = Find(edge[i].v);
      if (fx != fy) {
        cnt++;
        if (edge[i].w <= k)
          ans = min(ans, 1LL * k - edge[i].w);
        else {
          res += edge[i].w - k;
          f = 1;
        }
        fa[fx] = fy;
      }
      if (cnt == n - 1) break;
    }
    if (f == 1) {
      if (ans == inf)
        ans = res;
      else
        ans += res;
    } else {
      for (int i = 1; i <= m; i++) {
        if (edge[i].w > k) {
          ans = min(edge[i].w - 1LL * k, ans);
          break;
        }
      }
    }
    printf("%lld\n", ans);
  }
  return 0;
}
