#include <bits/stdc++.h>
using namespace std;
const int N = 200020, M = 2 * N;
int n, m, k, t, cnt1;
int p[N], f[N];
struct Edge {
  int a, b, w;
  bool operator<(const Edge &W) const { return w < W.w; }
} edges[M];
int find(int x) {
  if (p[x] != x) p[x] = find(p[x]);
  return p[x];
}
int kruskal() {
  sort(edges, edges + m);
  for (int i = 1; i <= n; i++) p[i] = i;
  int ans = 0;
  for (int i = 0; i < m; i++) {
    int a = find(edges[i].a), b = find(edges[i].b), w = edges[i].w;
    if (a != b) {
      p[a] = b;
      ans = max(ans, w);
      if (w > k) f[++cnt1] = w;
    }
  }
  return ans;
}
int main() {
  cin >> t;
  while (t--) {
    cnt1 = 0;
    cin >> n >> m >> k;
    for (int i = 1; i <= n; i++) p[i] = i;
    int ans0 = 1e9, ans1;
    for (int i = 1; i <= m; i++) {
      cin >> edges[i].a >> edges[i].b >> edges[i].w;
      ans0 = min(ans0, abs(k - edges[i].w));
    }
    ans1 = kruskal();
    if (ans1 <= k) {
      cout << min(k - ans1, ans0) << endl;
      ;
    } else {
      long long res = 0;
      for (int i = 1; i <= cnt1; i++) {
        res += (f[i] - k);
      }
      cout << res << endl;
    }
  }
}
