#include <bits/stdc++.h>
using namespace std;
const int N = 200005;
void solve() {
  int n, m, k;
  cin >> n >> m >> k;
  int ans = (1 << 30);
  for (int i = (1); i <= (m); ++i) {
    int a, b, s;
    cin >> a >> b >> s;
    ans = min(ans, abs(s - k));
  }
  cout << ans << endl;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  int q;
  cin >> q;
  while (q--) solve();
  return 0;
}
