#include <bits/stdc++.h>
using namespace std;
int inline read() {
  int num = 0, neg = 1;
  char c = getchar();
  while (!isdigit(c)) {
    if (c == '-') neg = -1;
    c = getchar();
  }
  while (isdigit(c)) {
    num = (num << 3) + (num << 1) + c - '0';
    c = getchar();
  }
  return num * neg;
}
const int maxn = 200010, mod = 998244353;
int T, n, m, k, fa[maxn];
struct Edge {
  int u, v, w;
} e[maxn];
bool cmp(Edge x, Edge y) { return x.w < y.w; }
int Find(int x) { return fa[x] == x ? x : fa[x] = Find(fa[x]); }
int main() {
  T = read();
  while (T--) {
    n = read();
    m = read();
    k = read();
    for (int i = 1; i <= m; i++) {
      e[i].u = read();
      e[i].v = read();
      e[i].w = abs(read() - k);
    }
    sort(e + 1, e + m + 1, cmp);
    for (int i = 1; i <= n; i++) fa[i] = i;
    int ans = 2147483647;
    for (int i = 1; i <= m; i++) {
      int u = Find(e[i].u), v = Find(e[i].v);
      if (u != v) ans = min(ans, e[i].w), fa[u] = v;
    }
    printf("%d\n", ans);
  }
  return 0;
}
