#include <bits/stdc++.h>
using namespace std;
int n, m, k, fa[200001], dep[200001];
void init(int num) {
  for (int i = 1; i <= num; i++) {
    fa[i] = i;
    dep[i] = 0;
  }
}
int found(int x) {
  if (fa[x] == x)
    return x;
  else
    return fa[x] = found(fa[x]);
}
bool same(int x, int y) { return found(x) == found(y); }
void add(int x, int y) {
  if (same(x, y)) return;
  if (dep[found(x)] < dep[found(y)])
    fa[found(x)] = found(y);
  else if (dep[found(x)] > dep[found(y)])
    fa[found(y)] = found(x);
  else
    fa[found(x)] = found(y), dep[found(x)]++;
}
struct lines {
  long long x, y, cost;
  bool operator<(const lines b) const { return cost < b.cost; }
} line[200001];
int t, minn = 0, pl;
int main() {
  ios::sync_with_stdio(0);
  cin >> t;
  while (t--) {
    minn = 0;
    cin >> n >> m >> k;
    init(n);
    for (int i = 1; i <= m; i++) {
      int x, y, co;
      cin >> x >> y >> co;
      co = co - k;
      line[i].x = x;
      line[i].y = y;
      line[i].cost = co;
    }
    sort(line + 1, line + m + 1);
    line[0].cost = -1;
    pl = 0;
    for (int i = 1; i <= m; i++) {
      if (line[i - 1].cost <= 0 && line[i].cost > 0) {
        pl = i;
        break;
      }
    }
    long long l = line[pl].cost, r = (long long)1e9, mid, ans = (long long)1e9;
    ;
    if (pl == 0) goto nxt;
    while (l <= r) {
      mid = (l + r) / 2;
      int loc = 0;
      init(n);
      while (line[++loc].cost <= mid && loc < m)
        ;
      for (int i = loc; i >= 1; i--) {
        add(line[i].x, line[i].y);
      }
      for (int i = 2; i <= n; i++) {
        if (!same(1, i)) {
          r = mid - 1;
          goto end;
        }
      }
      l = mid + 1;
      ans = line[loc].cost;
    end:;
    }
  nxt:
    if (pl == 0) pl = m + 1;
    init(n);
    for (int i = pl - 1; i >= 1; i--) {
      add(line[i].x, line[i].y);
    }
    for (int i = 2; i <= n; i++) {
      if (!same(1, i)) {
        goto end2;
      }
    }
    ans = min(ans, abs(line[pl - 1].cost));
  end2:;
    cout << ans << endl;
  }
}
