#include <bits/stdc++.h>
using namespace std;
constexpr int INF = 0x7fffffff;
constexpr int MAXN = 200005;
int _w, T, n, m, limit;
struct Edge {
  int u, v, w;
  Edge() {}
  Edge(int u, int v, int w) : u(u), v(v), w(w) {}
  bool operator<(const Edge &rhs) const { return w < rhs.w; }
} edge[MAXN];
namespace DSU {
int fa[MAXN];
int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); }
void init() {
  for (int i = 0; i <= n; ++i) fa[i] = i;
}
bool merge(int x, int y) {
  x = find(x);
  y = find(y);
  if (x == y) return 0;
  fa[y] = x;
  return 1;
}
}  // namespace DSU
int main() {
  _w = scanf("%d", &T);
  while (T--) {
    _w = scanf("%d%d%d", &n, &m, &limit);
    DSU::init();
    for (int i = 1; i <= m; ++i) {
      int x, y, z;
      _w = scanf("%d%d%d", &x, &y, &z);
      edge[i] = Edge(x, y, z);
    }
    sort(edge + 1, edge + m + 1);
    int maxv = 0, mindis = INF;
    stack<int> s;
    while (!s.empty()) s.pop();
    for (int i = 1; i <= m; ++i) {
      Edge &e = edge[i];
      mindis = min(mindis, abs(e.w - limit));
      if (!DSU::merge(e.u, e.v)) continue;
      maxv = max(maxv, e.w);
      s.push(e.w);
    }
    int flag = 0, ans = 0;
    while (!s.empty()) {
      int u = s.top();
      s.pop();
      if (u < limit) break;
      flag = 1;
      ans += u - limit;
    }
    if (!flag) ans += mindis;
    printf("%d\n", ans);
  }
  return 0;
}
