#include <bits/stdc++.h>
using namespace std;
void yes() {
  cout << "YES"
       << "\n";
}
void no() {
  cout << "NO"
       << "\n";
}
vector<int> p(200001);
vector<int> s(200001);
long long find(long long i) {
  if (i == p[i]) return i;
  p[i] = find(p[i]);
  return p[i];
}
void union1(long long i, long long j) {
  long long a = find(i);
  long long b = find(j);
  if (s[a] > s[b]) {
    p[b] = a;
    s[a] += s[b];
  } else {
    p[a] = b;
    s[b] += s[a];
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long t;
  cin >> t;
  while (t--) {
    long long n, m, k, a, b, c, d = 100000000000000000, res = 0, a1, b1, c1;
    cin >> n >> m >> k;
    vector<pair<long long, pair<int, int>>> v;
    for (int i = 1; i <= n; i++) {
      s[i] = 1;
      p[i] = i;
    }
    for (int i = 0; i < m; i++) {
      cin >> a >> b >> c;
      if (abs(k - c) < d) {
        d = abs(k - c);
        a1 = a;
        b1 = b;
        c1 = c;
      }
      v.push_back(make_pair(c, make_pair(a, b)));
    }
    sort(v.begin(), v.end());
    union1(a1, b1);
    bool b2 = 0;
    for (auto j : v) {
      c = j.first;
      a = j.second.first;
      b = j.second.second;
      if (find(a) != find(b)) {
        union1(a, b);
        if (c > k) {
          b2 = 1;
          res += c - k;
        }
      } else if (c > k && c == c1 && b2 == 0) {
        b2 = 1;
        res += c - k;
      }
    }
    if (b2 == 0) res += d;
    cout << res << "\n";
  }
  return 0;
}
