#include <bits/stdc++.h>
using namespace std;
long long exceeds, leastDiff, tc, n, m, k;
vector<vector<pair<int, int> > > adj;
bool taken[100050];
priority_queue<pair<int, int> > pq;
void process(int u) {
  taken[u] = 1;
  for (pair<int, int> edge : adj[u]) {
    if (!taken[edge.second]) pq.push(edge);
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> tc;
  while (tc--) {
    leastDiff = 1e18;
    exceeds = 0;
    memset(taken, 0, sizeof taken);
    cin >> n >> m >> k;
    adj.assign(n + 1, vector<pair<int, int> >());
    int u, v, w;
    for (int i = 0; i < m; i++) {
      cin >> u >> v >> w;
      adj[u].push_back({-w, v});
      adj[v].push_back({-w, u});
      if (leastDiff > abs(w - k)) leastDiff = abs(w - k);
    }
    process(1);
    while (!pq.empty()) {
      pair<int, int> edge = pq.top();
      pq.pop();
      if (taken[edge.second]) continue;
      process(edge.second);
      exceeds += max(0LL, -(edge.first + k));
    }
    if (exceeds == 0)
      cout << leastDiff << '\n';
    else
      cout << exceeds << '\n';
  }
}
