#include <bits/stdc++.h>
using namespace std;
int parent[200001], dist[200001];
int find(int a) {
  if (a == parent[a]) return a;
  return parent[a] = find(parent[a]);
}
bool merge(int a, int b) {
  a = find(a);
  b = find(b);
  if (a != b) {
    if (dist[a] < dist[b]) swap(a, b);
    parent[b] = a;
    dist[a] += dist[b];
    return true;
  }
  return false;
}
struct edge {
  int u, v, w;
  bool operator<(edge const &other) { return w < other.w; }
};
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n, m, k;
    cin >> n >> m >> k;
    for (int i = 1; i <= n; i++) {
      parent[i] = i;
      dist[i] = 0;
    }
    vector<edge> v(m + 1);
    int best = INT_MAX;
    for (int i = 1; i <= m; i++) {
      int a, b, c;
      cin >> a >> b >> c;
      v[i].u = a;
      v[i].v = b;
      v[i].w = c;
      best = min(best, abs(c - k));
    }
    cout << best << '\n';
  }
}
