#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const long double PI = acos((long double)-1);
const int maxN = 2e5 + 1;
struct Edge {
  int u, v, w;
};
vector<Edge> bigEdges, smallEdges;
vector<int> adj[maxN];
vector<int> parent(maxN), r(maxN);
long long ans = 0;
int y = INT_MAX;
int n, m, k;
int getParent(int a) {
  return (parent[a] = (parent[a] == a) ? a : getParent(parent[a]));
}
void unite(int a, int b) {
  if (r[a] < r[b]) {
    swap(a, b);
  }
  parent[b] = a;
  r[a] += r[b];
}
bool compare(Edge A, Edge B) { return A.w < B.w; }
bool compare2(Edge A, Edge B) { return A.w > B.w; }
void go() {
  for (int i = 0; i < (int)smallEdges.size(); ++i) {
    Edge E = smallEdges[i];
    y = min(y, abs(E.w - k));
  }
  for (int i = 0; i < (int)bigEdges.size(); ++i) {
    Edge E = bigEdges[i];
    y = min(y, abs(E.w - k));
  }
  cout << y << '\n';
}
void dfs(int v, vector<bool>& visited) {
  visited[v] = true;
  for (int to : adj[v]) {
    if (!visited[to]) {
      dfs(to, visited);
    }
  }
}
bool isConnected() {
  vector<bool> visited(maxN);
  dfs(1, visited);
  for (int i = 1; i <= n; ++i) {
    if (!visited[i]) return false;
  }
  return true;
}
void solve() {
  cin >> n >> m >> k;
  for (int i = 0; i <= n; ++i) {
    adj[i].clear();
    parent[i] = i;
    r[i] = 1;
  }
  y = INT_MAX;
  bigEdges.clear();
  smallEdges.clear();
  ans = 0;
  for (int i = 0; i < m; ++i) {
    int u, v, w;
    cin >> u >> v >> w;
    Edge E;
    E.u = u, E.v = v, E.w = w;
    if (w <= k) {
      smallEdges.push_back(E);
      adj[u].push_back(v);
      adj[v].push_back(u);
    } else {
      bigEdges.push_back(E);
    }
  }
  sort((bigEdges).begin(), (bigEdges).end(), compare2);
  if (!isConnected()) {
    for (int i = 0; i < (int)smallEdges.size(); ++i) {
      Edge E = smallEdges[i];
      int u = E.u, v = E.v;
      u = getParent(u), v = getParent(v);
      if (u != v) {
        unite(u, v);
      }
    }
    for (int i = 0; i < (int)bigEdges.size(); ++i) {
      Edge E = bigEdges[i];
      int u = E.u, v = E.v, w = E.w;
      u = getParent(u), v = getParent(v);
      if (u != v) {
        ans += abs(k - w);
        unite(u, v);
      }
    }
    cout << ans << '\n';
    return;
  }
  go();
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
