#include <bits/stdc++.h>
using namespace std;
template <typename T>
void read(T &x) {
  int s = 0, c = getchar();
  x = 0;
  while (isspace(c)) c = getchar();
  if (c == 45) s = 1, c = getchar();
  while (isdigit(c)) x = (x << 3) + (x << 1) + (c ^ 48), c = getchar();
  if (s) x = -x;
}
template <typename T>
void write(T x, char c = ' ') {
  int b[40], l = 0;
  if (x < 0) putchar(45), x = -x;
  while (x > 0) b[l++] = x % 10, x /= 10;
  if (!l) putchar(48);
  while (l) putchar(b[--l] | 48);
  putchar(c);
}
int findfa(int x, vector<int> &fa) {
  return x == fa[x] ? x : fa[x] = findfa(fa[x], fa);
}
int main(void) {
  int kase;
  read(kase);
  for (int ii = 1; ii <= kase; ii++) {
    int n, m, k;
    read(n);
    read(m);
    read(k);
    vector<pair<int, pair<int, int>>> edge(m);
    for (int u, v, w, i = 0; i < m; ++i) {
      read(u);
      read(v);
      read(w);
      --u;
      --v;
      edge[i] = make_pair(w, make_pair(u, v));
    }
    sort(edge.begin(), edge.end(),
         [](pair<int, pair<int, int>> &a, pair<int, pair<int, int>> &b) {
           return a.first < b.first;
         });
    vector<int> fa(n);
    iota(fa.begin(), fa.end(), 0);
    size_t id = 0;
    int cnt = 0;
    for (; id < edge.size(); ++id) {
      if (edge[id].first > k) break;
      auto a = findfa(edge[id].second.first, fa);
      auto b = findfa(edge[id].second.second, fa);
      if (a != b) {
        ++cnt;
        fa[a] = b;
      }
    }
    int ans = 0;
    if (cnt >= n - 1) {
      ans = k - edge[id - 1].first;
      if (id != edge.size()) ans = min(ans, edge[id].first - k);
    } else {
      for (; id < edge.size(); ++id) {
        if (cnt == n - 1) break;
        auto a = findfa(edge[id].second.first, fa);
        auto b = findfa(edge[id].second.second, fa);
        if (a != b) {
          ans += edge[id].first - k;
          ++cnt;
          fa[a] = b;
        }
      }
    }
    write(ans, '\n');
  }
  return 0;
}
