#include <bits/stdc++.h>
const long long MOD = 1e9 + 7;
const long long EPS = 1e-9;
const long double PI = acos(-1.0);
const int MAXX = 2e5 + 7;
const int LOGMAXX = 30;
using namespace std;
int n, m, k;
vector<int> par, rnk;
vector<bool> removed;
vector<pair<int, int>> farest;
vector<pair<pair<int, int>, int>> edges;
bool specified = false;
void init() {
  farest.assign(n + 1, {-1, -1});
  par.assign(n + 1, 0);
  rnk.assign(n + 1, 0);
  edges.assign(m, {{-1, -1}, -1});
  removed.assign(m, false);
  for (int i = 0; i <= n; i++) par[i] = i;
}
int getC(int u) { return par[u] == u ? u : par[u] = getC(par[u]); }
pair<int, int> chooseWeaker(pair<int, int> lhs, pair<int, int> rhs) {
  int d1 = lhs.first - k, d2 = rhs.first - k;
  if (d1 >= 0 && d2 >= 0) {
    return d1 > d2 ? lhs : rhs;
  }
  if (d1 < 0 && d2 < 0) {
    return d1 > d2 ? rhs : lhs;
  }
  if (specified) {
    return d1 > 0 ? lhs : rhs;
  }
  return abs(d2) > abs(d1) ? rhs : lhs;
}
pair<int, int> chooseWeaker(pair<int, int> lhs, pair<int, int> rhs,
                            pair<int, int> added) {
  if (lhs.first == -1 && rhs.first == -1) {
    return added;
  }
  if (lhs.first == -1) {
    return chooseWeaker(rhs, added);
  }
  if (rhs.first == -1) {
    return chooseWeaker(lhs, added);
  }
  return chooseWeaker(chooseWeaker(lhs, rhs), added);
}
int unitC(int u, int v, int speed = 0, int idx = 0) {
  int i = getC(u), j = getC(v);
  if (i != j) {
    if (rnk[i] > rnk[j]) {
      par[j] = i;
      farest[i] = chooseWeaker(farest[i], farest[j], {speed, idx});
    } else {
      par[i] = j;
      farest[j] = chooseWeaker(farest[i], farest[j], {speed, idx});
      if (rnk[i] == rnk[j]) rnk[j]++;
    }
    return -1;
  } else {
    pair<int, int> tr = chooseWeaker(farest[i], {speed, idx});
    if (tr.second != idx) {
      farest[i] = tr;
    }
    return tr.second;
  }
}
int main() {
  int nCase;
  cin >> nCase;
  while (nCase--) {
    cin >> n >> m >> k;
    init();
    for (auto& edge : edges)
      cin >> edge.first.first >> edge.first.second >> edge.second;
    for (int i = 0; i < m; i++) {
      auto& edge = edges[i];
      if (edge.second == k) specified = true;
      int toRemove = unitC(edge.first.first, edge.first.second, edge.second, i);
      if (toRemove != -1) {
        removed[toRemove] = true;
      }
    }
    set<int> rem;
    long long res = 0;
    for (int i = 0; i < m; i++) {
      if (!removed[i]) rem.insert(edges[i].second);
    }
    auto it = rem.upper_bound(k);
    if (it != rem.end()) {
      while (it != rem.end()) {
        res += (*it - k);
        it++;
      }
    } else {
      res += (k - *rem.rbegin());
    }
    cout << res << endl;
  }
  return 0;
}
