#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
struct edge {
  int u, to, nxt, w;
} e[2 * maxn], E[2 * maxn];
int head[maxn], cnt, headr[2 * maxn], cntr;
int x, y;
bool vis[maxn];
bool cmp(edge a, edge b) { return a.w < b.w; }
void add(int x, int y, int w) {
  e[++cnt].u = x;
  e[cnt].to = y;
  e[cnt].w = w;
  e[cnt].nxt = head[x];
  head[x] = cnt;
}
void addr(int x, int y) {
  E[++cntr].to = y;
  E[cntr].nxt = headr[x];
  headr[x] = cntr;
}
void init() {
  memset(e, 0, sizeof e);
  memset(E, 0, sizeof E);
  memset(head, 0, sizeof head);
  memset(headr, 0, sizeof headr);
  memset(vis, 0, sizeof vis);
  cnt = cntr = 0;
}
int n, m, k;
bool bfs() {
  queue<int> q;
  q.push(1);
  while (!q.empty()) {
    int u = q.front();
    q.pop();
    vis[u] = 1;
    for (int i = headr[u]; i; i = E[i].nxt) {
      int v = E[i].to;
      if (!vis[v]) {
        q.push(v);
        vis[v] = 1;
      }
    }
  }
  for (int i = 1; i <= n; i++) {
    if (!vis[i]) return 0;
  }
  return 1;
}
int f[maxn];
int root(int u) { return f[u] == u ? u : f[u] = root(f[u]); }
int main() {
  int t;
  cin >> t;
  while (t--) {
    init();
    cin >> n >> m >> k;
    int ans = 1e9, res = 1e9;
    for (int i = 1; i <= m; i++) {
      int x, y, z;
      cin >> x >> y >> z;
      if (z <= k) {
        addr(x, y);
        addr(y, x);
        res = min(res, k - z);
      }
      add(x, y, max(0, z - k));
      add(y, x, max(0, z - k));
      ans = min(ans, abs(k - z));
    }
    if (bfs()) {
      ans = min(ans, res);
      cout << ans << endl;
    } else {
      long long rr = 0;
      sort(e + 1, e + m + 1, cmp);
      for (int i = 1; i <= n; i++) f[i] = i;
      for (int i = 1; i <= m; i++) {
        x = e[i].u;
        y = e[i].to;
        if (root(x) != root(y)) {
          rr += e[i].w;
          f[root(x)] = root(y);
        }
      }
      cout << rr << endl;
    }
  }
}
