#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long t;
  cin >> t;
  while (t--) {
    long long n, m, k;
    cin >> n >> m >> k;
    long long parent[n + 1];
    long long size[n + 1];
    for (long long i = 0; i < n + 1; i++) {
      parent[i] = i;
      size[i] = 1;
    }
    vector<pair<long long, pair<long long, long long> > > v;
    long long mexx = 1e10;
    long long temp;
    vector<pair<long long, pair<long long, long long> > > ans;
    for (long long i = 0; i < m; i++) {
      long long a, b, c;
      cin >> a >> b >> c;
      v.push_back({c, {a, b}});
      if (abs(k - c) <= mexx) {
        mexx = abs(k - c);
        temp = i;
      }
    }
    ans.push_back(
        {v[temp].first, {v[temp].second.first, v[temp].second.second}});
    parent[v[temp].second.second] = v[temp].second.first;
    size[v[temp].second.first] = 2;
    long long summ = 0;
    long long tempmex = -1;
    if (v[temp].first >= k) {
      summ += abs(k - v[temp].first);
      tempmex = v[temp].first;
    }
    sort(v.begin(), v.end());
    long long sum = 1;
    for (long long i = 0; i < n; i++) {
      if (sum == n - 1) break;
      long long p1, p2;
      long long temp1 = v[i].second.first, temp2 = v[i].second.second;
      while (parent[temp1] != temp1) {
        temp1 = parent[temp1];
      }
      while (parent[temp2] != temp2) {
        temp2 = parent[temp2];
      }
      if (temp1 != temp2) {
        sum++;
        if (size[temp2] >= size[temp1]) {
          size[temp2] += size[temp1];
          parent[v[i].second.first] = temp2;
          parent[temp1] = temp2;
        } else {
          size[temp1] += size[temp2];
          parent[v[i].second.second] = temp1;
          parent[temp2] = temp1;
        }
        tempmex = max(tempmex, v[i].first);
        if (v[i].first > k) summ += v[i].first - k;
      }
      if (sum == n - 1) break;
    }
    if (tempmex < k) summ += mexx;
    cout << summ << endl;
  }
  return 0;
}
