#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
int pre[maxn];
int Find(int x) { return x == pre[x] ? x : pre[x] = Find(pre[x]); }
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n, m, k;
    scanf("%d%d%d", &n, &m, &k);
    vector<vector<int>> low, high;
    for (int i = 1; i <= n; ++i) pre[i] = i;
    for (int i = 1, a, b, c; i <= m; ++i) {
      scanf("%d%d%d", &a, &b, &c);
      if (c <= k) {
        low.push_back({a, b, c});
      } else
        high.push_back({a, b, c});
    }
    sort(low.begin(), low.end(),
         [](vector<int> a, vector<int> b) -> bool { return a[2] > b[2]; });
    sort(high.begin(), high.end(),
         [](vector<int> a, vector<int> b) -> bool { return a[2] < b[2]; });
    int mx = 0;
    int cnt = 0;
    for (auto &a : low) {
      int x = Find(a[0]);
      int y = Find(a[1]);
      if (x != y) {
        pre[x] = y;
        mx = max(mx, a[2]);
        cnt++;
      }
    }
    int ans = k - mx;
    if (cnt == n - 1) {
      for (auto &x : high) {
        if (x[2] - k < k - mx) ans = x[2] - k;
        break;
      }
    } else {
      for (auto &a : high) {
        int x = Find(a[0]);
        int y = Find(a[1]);
        if (x != y) {
          pre[x] = y;
          mx = max(mx, a[2]);
          cnt++;
        }
      }
      ans = mx - k;
    }
    printf("%d\n", ans);
  }
  return 0;
}
