#include <bits/stdc++.h>
using namespace std;
inline int add(int a, int b) {
  a += b;
  if (a >= 1000000007) a -= 1000000007;
  return a;
}
inline int mul(int a, int b) { return (a * 1ll * b) % 1000000007; }
inline int power(int a, int b) {
  int rt = 1;
  while (b > 0) {
    if (b & 1) rt = mul(rt, a);
    a = mul(a, a);
    b >>= 1;
  }
  return rt;
}
inline bool prime(long long int n) {
  if (n == 2) return true;
  long long int i;
  for (long long int i = 2; i < sqrt(n) + 1; i++) {
    if (n % i == 0) return false;
  }
  return true;
}
vector<long long int> primeFactors(long long int n) {
  vector<long long int> ans;
  while (n % 2 == 0) {
    ans.push_back(2);
    n = n / 2;
  }
  for (long long int i = 3; i <= sqrt(n); i = i + 2) {
    while (n % i == 0) {
      ans.push_back(i);
      n = n / i;
    }
  }
  if (n > 2) ans.push_back(n);
  return ans;
}
inline vector<long long int> all_primes(long long int n) {
  vector<bool> marked(n + 1, true);
  marked[0] = false;
  marked[1] = false;
  for (long long int i = 2; i <= n; i++) {
    if (marked[i]) {
      for (long long int j = i * i; j <= n; j += i) {
        marked[j] = false;
      }
    }
  }
  vector<long long int> v;
  for (long long int i = 0; i <= n; i++) {
    if (marked[i]) v.push_back(i);
  }
  return v;
}
string decToBin(long long int n, long long int length) {
  string s = "";
  long long int cnt = 0;
  while (n > 0) {
    s += to_string(n % 2);
    n = n / 2;
    cnt++;
  }
  reverse(s.begin(), s.end());
  string temp = string(length - cnt, '0');
  s = temp + s;
  return s;
}
void _25_din_me_rating_double() {
  long long int n, m, k;
  cin >> n >> m >> k;
  vector<long long int> wei;
  while (m--) {
    long long int x, y, w;
    cin >> x >> y >> w;
    wei.push_back(abs(w - k));
  }
  long long int ans = *min_element(wei.begin(), wei.end());
  cout << ans << "\n";
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  ;
  long long int t = 1;
  cin >> t;
  while (t--) {
    _25_din_me_rating_double();
  }
  return 0;
}
