#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int>> ed;
vector<long long int> wt;
unordered_map<int, int> leader;
unordered_map<int, int> Rank;
int n, m, k;
pair<int, int> closest;
int find(int x) {
  if (leader[x] == x) {
    return x;
  } else {
    leader[x] = find(leader[x]);
    return leader[x];
  }
}
void Union(int u, int v) {
  int x = find(u);
  int y = find(v);
  if (x == y) {
    return;
  }
  if (Rank[x] > Rank[y]) {
    leader[y] = x;
  } else if (Rank[x] < Rank[y]) {
    leader[x] = y;
  } else {
    leader[y] = x;
    ++Rank[x];
  }
}
void initialize(multimap<long long int, pair<int, int>> m) {
  for (auto i : m) {
    leader[i.second.first] = i.second.first;
    leader[i.second.second] = i.second.second;
    Rank[i.second.first] = 0;
    Rank[i.second.second] = 0;
  }
}
long long int ans = 0;
void kruskals() {
  multimap<long long int, pair<int, int>> m;
  for (int i = 0; i < ed.size(); ++i) {
    m.insert(make_pair(wt[i], make_pair(ed[i].first, ed[i].second)));
  }
  initialize(m);
  leader[closest.first] = closest.second;
  leader[closest.second] = closest.second;
  Rank[closest.second] = 1;
  Rank[closest.first] = 0;
  for (auto i = m.begin(); i != m.end(); ++i) {
    if (find(i->second.first) != find(i->second.second)) {
      Union(i->second.first, (i->second.second));
      ans += i->first;
    }
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  int q = 0;
  while (t--) {
    ++q;
    cin >> n >> m >> k;
    long long int a, b, w;
    long long int mini = LONG_MAX;
    long long int edv = -1;
    for (int i = 0; i < m; ++i) {
      cin >> a >> b >> w;
      if (a == b) {
        continue;
      }
      if (abs(k - w) < mini) {
        if (mini != LONG_MAX) {
          ed.push_back(make_pair(closest.first, closest.second));
          if (edv > k) {
            wt.push_back(edv - k);
          } else {
            wt.push_back(0);
          }
        }
        mini = abs(k - w);
        closest.first = a - 1;
        closest.second = b - 1;
        edv = w;
      } else {
        ed.push_back(make_pair(a - 1, b - 1));
        if (w > k) {
          wt.push_back(w - k);
        } else {
          wt.push_back(0);
        }
      }
    }
    ans = 0;
    kruskals();
    cout << ans + mini << "\n";
    ed.clear();
    wt.clear();
    leader.clear();
    Rank.clear();
  }
  return 0;
}
