#include <bits/stdc++.h>
using namespace std;
void setIO(string str, bool dbg) {
  ios_base::sync_with_stdio(0);
  cin.tie(nullptr);
  cout.tie(nullptr);
  if (!dbg) {
    freopen((str + ".in").c_str(), "r", stdin);
    freopen((str + ".out").c_str(), "w", stdout);
  }
}
const int MAX = 2e5 + 5;
const int LEN = 5e2 + 0;
const int LVL = 2e1 + 0;
const long long int MOD = 1e9 + 7;
const long long int INF = 2e9;
int xyz = 1;
int n, m, k;
int ids[MAX];
int rnk[MAX];
int vst[MAX];
vector<pair<int, int> > con[MAX];
int fnd(int x) {
  if (x == ids[x]) return x;
  return ids[x] = fnd(ids[x]);
}
void unn(int a, int b) {
  a = fnd(a);
  b = fnd(b);
  ids[b] = a;
  if (a == b) return;
  rnk[a] += rnk[b];
}
long long int mst() {
  priority_queue<pair<int, int> > que;
  long long int ans = 0;
  que.push({0, 1});
  while (!que.empty()) {
    auto node = que.top();
    que.pop();
    long long int cst = node.first;
    int pos = node.second;
    cout << pos << " " << cst << endl;
    if (vst[pos]) continue;
    ans += cst;
    vst[pos] = true;
    for (auto adj : con[pos])
      if (!vst[adj.first]) que.push({min(0, k - adj.second), adj.first});
  }
  return -ans;
}
void run() {
  cin >> n >> m >> k;
  for (int i = 1; i <= n; i++) ids[i] = i, rnk[i] = 1, vst[i] = 0;
  for (int i = 1; i <= n; i++) con[i].clear();
  for (int i = 1; i <= m; i++) {
    int u;
    int v;
    int w;
    cin >> u >> v >> w;
    con[u].push_back({v, w});
    con[v].push_back({u, w});
    if (w <= k) unn(u, v);
  }
  bool full = rnk[fnd(1)] == n;
  if (!full) {
    cout << mst() << endl;
    return;
  }
  int ans = INF;
  for (int pos = 1; pos <= n; pos++)
    for (auto edg : con[pos]) ans = min(ans, abs(edg.second - k));
  cout << ans << "\n";
}
int main() {
  setIO("", 1);
  cin >> xyz;
  while (xyz--) run();
  return 0;
}
