#include<bits/stdc++.h>
using namespace std;
 
typedef vector <int> vi;
typedef pair< int ,int > pii;
#define endl "\n"
#define sd(val) scanf("%d",&val)
#define ss(val) scanf("%s",&val)
#define sl(val) scanf("%lld",&val)
#define debug(val) printf("check%d\n",val)
#define all(v) v.begin(),v.end()
#define PB push_back
#define MP make_pair
#define FF first
#define SS second
#define ll long long
#define MOD 1000000007
#define clr(val) memset(val,0,sizeof(val))
#define what_is(x) cerr << #x << " is " << x << endl;
#define OJ \
    freopen("input.txt", "r", stdin); \
    freopen("output.txt", "w", stdout);
#define FIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);


void make_set(int v,vector<int>&parent,vector<int>&rank) {
    parent[v] = v;
    rank[v] = 0;
}

int find_set(int v,vector<int>&parent) {
    if (v == parent[v])
        return v;
    return parent[v] = find_set(parent[v],parent);
}


bool union_sets(int a, int b,vector<int>&parent,vector<int>&rank) {
    a = find_set(a,parent);
    b = find_set(b,parent);
    if (a != b) {
        if (rank[a] < rank[b])
            swap(a, b);
        parent[b] = a;
        if (rank[a] == rank[b])
            rank[a]++;
        return true;
    }
    return false;
}
 
int main()
{
  FIO
  int tt;cin>>tt;
  while(tt--){
      
      int n,m,k;
      cin>>n>>m>>k;
      int o=-1;
      ll ans=MOD;
      vector<vector<int>>gg(m,vector<int>(3));
      for(int i=0;i<m;i++){
          int v,u,w;
          cin>>v>>u>>w;
          v--;
          u--;
          gg[i][0]=w;
          gg[i][1]=v;
          gg[i][2]=u;
         
      }


      vector<int>rank(n,0);
      vector<int>parent(n,-1);

      for(int i=0;i<n;i++)
        make_set(i,parent,rank);


      sort(gg.begin(),gg.end());
      
      
      for(int i=0;i<m;i++){
          if(abs(k-gg[i][0])<ans){
              o=i;
              ans=abs(k-gg[i][0]);
          }
      }

      
      int pp=0;
      ans=0;
      for(int i=0;i<m;i++){
           if(union_sets(gg[i][1],gg[i][2],parent,rank)){
                if(gg[i][0]>k)ans+=gg[i][0]-k;
                
           }
      }
      if(ans==0)ans=abs(k-gg[o][0]);
      
    
     
      cout<<ans<<'\n';


    
  }
 
 
 
return 0;
   
}