There are $n$ cities and $m$ bidirectional roads in Berland. The $i$-th road connects the cities $x_i$ and $y_i$, and has the speed limit $s_i$. The road network allows everyone to get from any city to any other city.

The Berland Transport Ministry is planning a road reform.

First of all, maintaining all $m$ roads is too costly, so $m - (n - 1)$ roads will be demolished in such a way that the remaining $(n - 1)$ roads still allow to get to any city from any other city. Formally, the remaining roads should represent an undirected tree.

Secondly, the speed limits on the remaining roads might be changed. The changes will be done sequentially, each change is either increasing the speed limit on some road by $1$, or decreasing it by $1$. Since changing the speed limit requires a lot of work, the Ministry wants to minimize the number of changes.

The goal of the Ministry is to have a road network of $(n - 1)$ roads with the maximum speed limit over all roads equal to exactly $k$. They assigned you the task of calculating the minimum number of speed limit changes they have to perform so the road network meets their requirements.

For example, suppose the initial map of Berland looks like that, and $k = 7$:

Then one of the optimal courses of action is to demolish the roads $1$–$4$ and $3$–$4$, and then decrease the speed limit on the road $2$–$3$ by $1$, so the resulting road network looks like that:


-----Input-----

The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases.

The first line of each test case contains three integers $n$, $m$ and $k$ ($2 \le n \le 2 \cdot 10^5$; $n - 1 \le m \le \min(2 \cdot 10^5, \frac{n(n-1)}{2})$; $1 \le k \le 10^9$) — the number of cities, the number of roads and the required maximum speed limit, respectively.

Then $m$ lines follow. The $i$-th line contains three integers $x_i$, $y_i$ and $s_i$ ($1 \le x_i, y_i \le n$; $x_i \ne y_i$; $1 \le s_i \le 10^9$) — the cities connected by the $i$-th road and the speed limit on it, respectively. All roads are bidirectional.

The road network in each test case is connected (that is, it is possible to reach any city from any other city by traveling along the road), and each pair of cities is connected by at most one road.

The sum of $n$ over all test cases does not exceed $2 \cdot 10^5$. Similarly, the sum of $m$ over all test cases does not exceed $2 \cdot 10^5$.


-----Output-----

For each test case, print one integer — the minimum number of changes the Ministry has to perform so that the maximum speed limit among the remaining $(n - 1)$ roads is exactly $k$.


-----Examples-----

Input
4
4 5 7
4 1 3
1 2 5
2 3 8
2 4 1
3 4 4
4 6 5
1 2 1
1 3 1
1 4 2
2 4 1
4 3 1
3 2 1
3 2 10
1 2 8
1 3 10
5 5 15
1 2 17
3 1 15
2 3 10
1 4 14
2 5 8
Output
1
3
0
0


-----Note-----

The explanation for the example test:

The first test case is described in the problem statement.

In the second test case, the road network initially looks like that:

The Ministry can demolish the roads $1$–$2$, $3$–$2$ and $3$–$4$, and then increase the speed limit on the road $1$–$4$ three times.

In the third test case, the road network already meets all the requirements.

In the fourth test case, it is enough to demolish the road $1$–$2$ so the resulting road network meets the requirements.

Difficulty: MEDIUM_HARD
Tags: Spanning trees

Graph algorithms

Greedy algorithms
Skill types: Greedy algorithms

Starter code:

Solutions:
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
import time
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())

def getMat(n):
	return [getInts() for _ in range(n)]

def isInt(s):
	return '0' <= s[0] <= '9'
MOD = 10 ** 9 + 7

def solve():
	(N, M, K) = getInts()
	edges = []
	for m in range(M):
		(x, y, s) = getInts()
		edges.append((s, x - 1, y - 1))
	edges.sort()

	def find(a):
		if a != p[a]:
			p[a] = find(p[a])
		return p[a]

	def union(a, b):
		(a, b) = (find(a), find(b))
		if a == b:
			return
		if size[a] > size[b]:
			(a, b) = (b, a)
		p[a] = b
		size[b] += size[a]
		return
	p = [i for i in range(N)]
	size = [1] * N
	ans1 = 0
	best = 10 ** 18
	best_ind = -1
	i = 0
	for (s, x, y) in edges:
		if find(x) != find(y):
			union(x, y)
			ans1 += max(0, s - K)
			max_used = s
		diff = abs(s - K)
		if diff < best:
			best = diff
			best_ind = i
		i += 1
	if not ans1:
		ans1 += abs(K - max_used)
	ans2 = best
	i = 0
	p = [i for i in range(N)]
	size = [1] * N
	(s, x, y) = edges[best_ind]
	union(x, y)
	for (s, x, y) in edges:
		if find(x) != find(y):
			union(x, y)
			ans2 += max(0, s - K)
	return min(ans1, ans2)
for _ in range(getInt()):
	print(solve())


import math
from sys import stdin

def uf_find(n, p):
	ufl = []
	while p[n] != n:
		ufl.append(n)
		n = p[n]
	for i in ufl:
		p[i] = n
	return n

def uf_union(a, b, p, rank):
	ap = uf_find(a, p)
	bp = uf_find(b, p)
	if ap == bp:
		return True
	else:
		if rank[ap] > rank[bp]:
			p[bp] = ap
		elif rank[ap] < rank[bp]:
			p[ap] = bp
		else:
			p[bp] = ap
			rank[ap] += 1
		return False
tt = int(stdin.readline())
for loop in range(tt):
	(n, m, k) = map(int, stdin.readline().split())
	under = []
	over = []
	for i in range(m):
		(x, y, s) = map(int, stdin.readline().split())
		x -= 1
		y -= 1
		if s <= k:
			under.append((s, x, y))
		else:
			over.append((s, x, y))
	under.sort()
	over.sort()
	ans = float('inf')
	cnt = 0
	p = [i for i in range(n)]
	rank = [0] * n
	for (c, x, y) in under:
		if not uf_union(x, y, p, rank):
			cnt += 1
	if cnt == n - 1 and len(under) > 0:
		ans = min(ans, k - under[-1][0])
	if cnt != n - 1:
		tmpsum = 0
		for (c, x, y) in over:
			if not uf_union(x, y, p, rank):
				cnt += 1
				tmpsum += c - k
				if cnt == n - 1:
					ans = min(ans, tmpsum)
	elif len(over) > 0:
		ans = min(ans, over[0][0] - k)
	print(ans)


import sys
input = sys.stdin.readline

class UnionFind:

	def __init__(self, n):
		self.parent = list(range(n))

	def find(self, a):
		acopy = a
		while a != self.parent[a]:
			a = self.parent[a]
		while acopy != a:
			(self.parent[acopy], acopy) = (a, self.parent[acopy])
		return a

	def merge(self, a, b):
		self.parent[self.find(b)] = self.find(a)

def kruskal(n, U, V, W):
	union = UnionFind(n)
	(cost, merge_cnt) = (0, 0)
	(mst_u, mst_v, rej) = ([], [], [])
	order = sorted(range(len(W)), key=lambda x: W[x])
	for i in range(len(W)):
		(u, v, w) = (U[order[i]], V[order[i]], W[order[i]])
		(find_u, find_v) = (union.find(u), union.find(v))
		if find_u != find_v:
			cost += W[order[i]]
			merge_cnt += 1
			union.parent[find_v] = find_u
			mst_u.append(w)
		else:
			rej.append(w)
	rej.sort()
	return (mst_u, rej)
for _ in range(int(input())):
	(n, m, k) = map(int, input().split())
	X = []
	Y = []
	W = []
	for _ in range(m):
		(xi, yi, wi) = map(int, input().split())
		X.append(xi)
		Y.append(yi)
		W.append(wi)
	(u, v) = kruskal(len(X) + 2, X, Y, W)
	ans = 0
	closest1 = 100000000000
	closest2 = 0
	for i in v:
		if i >= k:
			closest1 = min(closest1, i)
		else:
			closest2 = max(closest2, i)
	if closest1 - k < k - closest2:
		closest = closest1
	else:
		closest = closest2
	flag = 0
	for i in u:
		if i >= k:
			flag = 1
			ans += i - k
	if not flag:
		ans = abs(closest - k)
		for i in u:
			ans = min(ans, k - i)
	print(ans)


from sys import stdin, stdout
from operator import itemgetter
import sys

class UnionFind:

	def __init__(self, n):
		self.parent = list(range(n))

	def find(self, a):
		acopy = a
		while a != self.parent[a]:
			a = self.parent[a]
		while acopy != a:
			(self.parent[acopy], acopy) = (a, self.parent[acopy])
		return a

	def union(self, a, b):
		self.parent[self.find(b)] = self.find(a)

def main():
	input = sys.stdin.buffer.readline
	t = int(input())
	for _ in range(t):
		(n, m, k) = [int(x) for x in input().split()]
		uf = UnionFind(n + 1)
		stack = 0
		v = []
		for _ in range(m):
			v.append([int(x) for x in input().split()])
		v.sort(key=itemgetter(2))
		min_speed = 10000000000
		for (a, b, s) in v:
			if uf.find(a) != uf.find(b):
				uf.union(a, b)
				stack += max(0, s - k)
		if stack != 0:
			stdout.write(str(stack) + '\n')
		else:
			for (a, b, s) in v:
				min_speed = min(min_speed, abs(s - k))
			stdout.write(str(min_speed) + '\n')
main()


import sys
input = sys.stdin.readline
from sys import stdin, stdout
from collections import defaultdict, Counter
M = 10 ** 9 + 7
import heapq
MAX = 200005
INF = 10 ** 20

def MST(n, s, adj):
	dist = [INF] * n
	visited = [0] * n
	ans = 0
	dist[s] = 0
	heap = [[0, s]]
	while heap:
		head = heapq.heappop(heap)
		u = head[1]
		if visited[u]:
			continue
		ans += head[0]
		visited[u] = 1
		for i in range(len(adj[u])):
			elem = adj[u][i]
			disv = elem[1]
			v = elem[0]
			if not visited[v] and disv < dist[v]:
				dist[v] = disv
				heapq.heappush(heap, [disv, v])
	return ans

def main():
	for _ in range(int(input())):
		(n, m, k) = [int(s) for s in input().split()]
		adj = [[] for i in range(n)]
		minwk = 10 ** 10
		for i in range(m):
			(u, v, w) = [int(s) for s in input().split()]
			adj[u - 1].append([v - 1, max(0, w - k)])
			adj[v - 1].append([u - 1, max(w - k, 0)])
			minwk = min(minwk, abs(k - w))
		w = MST(n, 0, adj)
		if w == 0:
			print(minwk)
		else:
			print(w)
main()


import sys
import math
import heapq
import bisect
from collections import Counter
from collections import defaultdict
from io import BytesIO, IOBase
import string

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None
		self.BUFSIZE = 8192

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def get_int():
	return int(input())

def get_ints():
	return list(map(int, input().split(' ')))

def get_int_grid(n):
	return [get_ints() for _ in range(n)]

def get_str():
	return input().split(' ')

def yes_no(b):
	if b:
		return 'YES'
	else:
		return 'NO'

def binary_search(good, left, right, delta=1, right_true=False):
	limits = [left, right]
	while limits[1] - limits[0] > delta:
		if delta == 1:
			mid = sum(limits) // 2
		else:
			mid = sum(limits) / 2
		if good(mid):
			limits[int(right_true)] = mid
		else:
			limits[int(~right_true)] = mid
	if good(limits[int(right_true)]):
		return limits[int(right_true)]
	else:
		return False

def prefix_sums(a, drop_zero=False):
	p = [0]
	for x in a:
		p.append(p[-1] + x)
	if drop_zero:
		return p[1:]
	else:
		return p

def prefix_mins(a, drop_zero=False):
	p = [float('inf')]
	for x in a:
		p.append(min(p[-1], x))
	if drop_zero:
		return p[1:]
	else:
		return p

class DSU:

	def __init__(self, nodes):
		self.p = [i for i in range(nodes)]
		self.r = [0 for i in range(nodes)]
		self.s = [1 for i in range(nodes)]

	def get(self, u):
		if u != self.p[u]:
			self.p[u] = self.get(self.p[u])
		return self.p[u]

	def union(self, u, v):
		u = self.get(u)
		v = self.get(v)
		if u != v:
			if self.r[u] > self.r[v]:
				(u, v) = (v, u)
			self.p[u] = v
			if self.r[u] == self.r[v]:
				self.r[v] += 1
			self.s[v] += self.s[u]

def solve_j():
	(n, m, k) = get_ints()
	edges = []
	for e in range(m):
		(x, y, s) = get_ints()
		edges.append((s, y, x))
	edges.sort()
	dsu = DSU(n)
	m = float('inf')
	M = 0
	for (s, y, x) in edges:
		m = min(m, abs(s - k))
		if s <= k:
			dsu.union(x - 1, y - 1)
		elif dsu.get(x - 1) != dsu.get(y - 1):
			dsu.union(x - 1, y - 1)
			M += max(0, abs(s - k))
	if not M:
		return m
	else:
		return M
t = get_int()
for _ in range(t):
	print(solve_j())


import sys
LI = lambda : list(map(int, sys.stdin.readline().split()))
MI = lambda : map(int, sys.stdin.readline().split())
SI = lambda : sys.stdin.readline().strip('\n')
II = lambda : int(sys.stdin.readline())

def find(v):
	global p
	tmp = v
	while p[tmp] != tmp:
		tmp = p[tmp]
	p[v] = tmp
	return tmp

def merge(a, b):
	global p, r
	(roota, rootb) = (find(a), find(b))
	if roota != rootb:
		if r[roota] > r[rootb]:
			p[rootb] = roota
			r[roota] += 1
		else:
			p[roota] = rootb
			r[rootb] += 1
for _ in range(II()):
	(n, m, k) = MI()
	g = []
	d = 10000000000.0
	for __ in range(m):
		(u, v, w) = MI()
		g.append((w, u, v))
		if abs(w - k) < d:
			d = abs(w - k)
	g.sort()
	(p, r) = ([i for i in range(n + 1)], [1 for i in range(n + 1)])
	ans = 0
	for (w, u, v) in g:
		if find(u) != find(v):
			merge(u, v)
			ans += max(0, w - k)
	print(ans if ans else d)


from sys import *
from bisect import bisect_left
input = stdin.readline

def root(node):
	while parent[node] >= 0:
		node = parent[node]
	return node

def union(x, y):
	(x1, x2) = (root(x), root(y))
	if parent[x1] < parent[x2]:
		parent[x1] += parent[x2]
		parent[x2] = x1
	else:
		parent[x2] += parent[x1]
		parent[x1] = x2

def kruskal():
	min_cost = 0
	for (x, y, cst) in edges:
		if root(x) != root(y):
			min_cost += max(cst - k, 0)
			union(x, y)
	return min_cost
for _ in range(int(input())):
	(n, m, k) = map(int, input().split())
	edges = list((list(map(int, input().split())) for i in range(m)))
	edges.sort(key=lambda x: x[2])
	parent = [-1] * (n + 1)
	cost = kruskal()
	if not cost:
		cost = k
		for i in range(m):
			cost = min(cost, abs(edges[i][2] - k))
	print(cost)


import os, sys
from io import BytesIO, IOBase

def find(parent, x):
	if x == parent[x]:
		return x
	parent[x] = find(parent, parent[x])
	return parent[x]

def union(parent, a, b, rank):
	(a, b) = (find(parent, a), find(parent, b))
	if a != b:
		if rank[a] < rank[b]:
			(a, b) = (b, a)
		parent[b] = a
		if rank[a] == rank[b]:
			rank[a] += 1
		return 1
	return 0

def main():
	for x in range(int(input())):
		(n, m, k) = map(int, input().split())
		ed = [tuple(map(int, input().split())) for _ in range(m)]
		ed1 = sorted(filter(lambda xx: xx[2] <= k, ed), key=lambda xx: xx[2], reverse=1)
		ed = sorted(filter(lambda xx: xx[2] > k, ed), key=lambda xx: xx[2])
		parent = list(range(n))
		rank = [0] * n
		conn = n
		ans = 0
		for i in ed1:
			(a, b) = (i[0] - 1, i[1] - 1)
			if union(parent, a, b, rank):
				conn -= 1
			if conn == 1:
				break
		if conn != 1:
			for i in ed:
				(a, b) = (i[0] - 1, i[1] - 1)
				if union(parent, a, b, rank):
					conn -= 1
					ans += i[2] - k
				if conn == 1:
					break
		elif not len(ed1):
			ans = abs(ed[0][2] - k)
		elif not len(ed):
			ans = abs(ed1[0][2] - k)
		else:
			ans = min(abs(ed1[0][2] - k), abs(ed[0][2] - k))
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def find(node):
	comp = []
	while group[node] != node:
		comp.append(node)
		node = group[node]
	for i in comp:
		group[i] = node
	return group[node]
for j in range(int(input())):
	(n, m, k) = map(int, input().split())
	group = [s for s in range(n)]
	info = []
	nearest = 10 ** 10
	for s in range(m):
		(x, y, s1) = map(int, input().split())
		x -= 1
		y -= 1
		if abs(k - s1) < abs(k - nearest):
			nearest = s1
		if s1 <= k:
			info.append((x, y, 0))
		else:
			info.append((x, y, s1 - k))
	info.sort(key=lambda x: x[2])
	ans = 0
	for s in range(m):
		edge = (info[s][0], info[s][1])
		cost = info[s][2]
		g1 = find(edge[0])
		g2 = find(edge[1])
		if g1 != g2:
			group[g2] = g1
			ans += cost
	if ans != 0:
		print(ans)
	else:
		print(abs(k - nearest))


import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def find(u):
	if parent[u] == u:
		return u
	parent[u] = find(parent[u])
	return parent[u]

def union(a, b):
	u = parent[a]
	v = parent[b]
	if size[u] > size[v]:
		parent[v] = u
		size[u] += size[v]
	else:
		parent[u] = v
		size[v] += size[u]
for _ in range(int(input())):
	(n, m, k) = map(int, input().split())
	edges = []
	for j in range(m):
		(u, v, s) = map(int, input().split())
		edges.append([s, u, v])
	edges.sort()
	ind1 = -1
	ind2 = -1
	for j in range(m):
		if edges[j][0] >= k:
			ind1 = j
			break
		else:
			ind2 = j
	ans = float('inf')
	if ind1 != -1:
		parent = [i for i in range(n + 1)]
		size = [1 for i in range(n + 1)]
		req = abs(edges[ind1][0] - k)
		(u, v) = (edges[ind1][1], edges[ind1][2])
		union(u, v)
		cnt = 1
		for e in range(m):
			if e != ind1:
				j = edges[e]
				if cnt == n - 1:
					break
				(val, u, v) = (j[0], j[1], j[2])
				if find(u) != find(v):
					union(u, v)
					cnt += 1
					if val > k:
						req += val - k
		ans = req
	ind1 = ind2
	if ind1 != -1:
		parent = [i for i in range(n + 1)]
		size = [1 for i in range(n + 1)]
		req = abs(k - edges[ind1][0])
		(u, v) = (edges[ind1][1], edges[ind1][2])
		if find(u) != find(v):
			union(u, v)
		cnt = 1
		for e in range(m):
			if e != ind1:
				j = edges[e]
				if cnt == n - 1:
					break
				(val, u, v) = (j[0], j[1], j[2])
				if find(u) != find(v):
					union(u, v)
					cnt += 1
					if val > k:
						req += val - k
		ans = min(ans, req)
	parent = [i for i in range(n + 1)]
	size = [1 for i in range(n + 1)]
	edges1 = []
	cnt = 0
	req = 0
	m = 0
	for j in edges:
		if cnt == n - 1:
			break
		(val, u, v) = (j[0], j[1], j[2])
		m = max(m, val)
		if find(u) != find(v):
			union(u, v)
			cnt += 1
			if val > k:
				req += val - k
	if m < k:
		req += abs(k - m)
	ans = min(ans, req)
	print(ans)


class UnionFind:

	def __init__(self, n):
		self.parent = list(range(n))

	def find(self, a):
		acopy = a
		while a != self.parent[a]:
			a = self.parent[a]
		while acopy != a:
			(self.parent[acopy], acopy) = (a, self.parent[acopy])
		return a

	def union(self, a, b):
		self.parent[self.find(b)] = self.find(a)
import sys
input = sys.stdin.buffer.readline

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))
allAns = []
t = int(input())
for _ in range(t):
	(n, m, k) = [int(x) for x in input().split()]
	uvw = []
	for __ in range(m):
		uvw.append([int(x) for x in input().split()])
	uvw.sort(key=lambda x: x[2])
	uf = UnionFind(n + 1)
	weights = []
	for (u, v, w) in uvw:
		if uf.find(u) != uf.find(v):
			weights.append(w)
			uf.union(u, v)
	ans = 0
	for w in weights:
		ans += max(0, w - k)
	if ans == 0:
		minDelta = float('inf')
		for (u, v, w) in uvw:
			minDelta = min(minDelta, abs(w - k))
		ans = minDelta
	allAns.append(ans)
multiLineArrayPrint(allAns)


class DSU:

	def __init__(self, n):
		self.uf = {i: i for i in range(n)}
		self.rank = {i: 1 for i in range(n)}

	def find(self, x):
		if self.uf[x] != x:
			self.uf[x] = self.find(self.uf[x])
		return self.uf[x]

	def union(self, x, y):
		(px, py) = (self.find(x), self.find(y))
		if px != py:
			if self.rank[px] > self.rank[py]:
				(px, py) = (py, px)
			self.rank[py] += self.rank[px]
			self.uf[px] = py
			return True
		return False
import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m, k) = map(int, input().split())
	A = [list(map(int, input().split())) for _ in range(m)]
	dsu = DSU(n)
	ans = 0
	A.sort(key=lambda x: x[2])
	for (x, y, a) in A:
		if dsu.union(x - 1, y - 1):
			ans += max(0, a - k)
	if not ans:
		ans = abs(min(A, key=lambda x: abs(x[2] - k))[2] - k)
	print(ans)


import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict, deque, Counter
from math import sqrt, pi, ceil, log, inf, gcd, floor
from itertools import combinations, permutations
from bisect import *
from fractions import Fraction
from heapq import *
from random import randint

def find(p, z):
	a = []
	while z != p[z]:
		a.append(z)
		z = p[z]
	for i in a:
		p[i] = z
	return z

def union(p, s, x, y):
	px = find(p, x)
	py = find(p, y)
	if px != py:
		if s[px] > s[py]:
			s[px] += s[py]
			p[py] = px
		else:
			s[py] += s[px]
			p[px] = py
		return 1
	return 0

def main():
	for t in range(int(input())):
		(n, m, k) = map(int, input().split())
		a = []
		for i in range(m):
			a.append(tuple(map(int, input().split())))
		a.sort(key=lambda x: x[2])
		p = [i for i in range(n + 1)]
		s = [1 for _ in range(n + 1)]
		(su, b, f, ma) = (0, 0, 0, 0)
		for i in a:
			z = union(p, s, i[0], i[1])
			if z:
				if i[2] > k:
					su += i[2]
					b += 1
				elif i[2] == k:
					f = 1
			if not f:
				if abs(ma - k) > abs(i[2] - k):
					ma = i[2]
		if f or b:
			print(su - b * k)
		else:
			print(abs(k - ma))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from collections import defaultdict
from math import ceil, sqrt, floor
from heapq import heappush, heappop
import sys
inf = float('inf')

class DisjointSet:

	def __init__(self, n):
		self.n = n
		self.par = [-1] * n
		self.nc = n

	def findParent(self, i):
		if self.par[i] == -1:
			return i
		else:
			var = self.findParent(self.par[i])
			self.par[i] = var
			return var

	def union(self, a, b):
		aPar = self.findParent(a)
		bPar = self.findParent(b)
		if aPar != bPar:
			self.par[aPar] = bPar
			self.nc -= 1

	def numComponents(self):
		return self.nc

def primMSTFaster(adj, source=0):
	edgesUsed = set()
	fringe = list()
	start = (0, source, None)
	heappush(fringe, start)
	mstSet = set()
	key = defaultdict(lambda : None)
	key[source] = 0
	while len(fringe) > 0:
		curTup = heappop(fringe)
		curCost = curTup[0]
		cur = curTup[1]
		curParent = curTup[2]
		if cur in mstSet:
			continue
		mstSet.add(cur)
		if curParent is not None:
			edgesUsed.add((curParent, cur, curCost))
		for neighborTup in adj[cur]:
			neighbor = neighborTup[0]
			cost = neighborTup[1]
			if cost != -1 and neighbor not in mstSet and (key[neighbor] is None or key[neighbor] > cost):
				key[neighbor] = cost
				heappush(fringe, (cost, neighbor, cur))
	return (edgesUsed, key)
t = int(input())
res = list()
for dsskfljl in range(t):
	splitted = [int(amit) for amit in sys.stdin.readline().split(' ')]
	n = splitted[0]
	m = splitted[1]
	k = splitted[2]
	ds = DisjointSet(n)
	edges = list()
	minDelta = inf
	minEdge = None
	for i in range(m):
		edge = [int(amit) for amit in sys.stdin.readline().split(' ')]
		if edge[2] <= k:
			ds.union(edge[0] - 1, edge[1] - 1)
		edges.append((edge[0], edge[1], edge[2]))
		if abs(edge[2] - k) < minDelta:
			minDelta = abs(edge[2] - k)
			minEdge = edge
	if ds.numComponents() == 1:
		totalCost = abs(minEdge[2] - k)
		res.append(str(totalCost))
	else:
		adj = list()
		for i in range(n):
			adj.append(set())
		for edge in edges:
			s = edge[0] - 1
			t = edge[1] - 1
			cost = max(0, edge[2] - k)
			adj[s].add((t, cost))
			adj[t].add((s, cost))
		mst = primMSTFaster(adj, 0)
		edgesUsed = mst[0]
		totalCost = 0
		for edge in edgesUsed:
			cost = edge[2]
			totalCost += cost
		res.append(str(totalCost))
sys.stdout.write('\n'.join(res))


import collections
import time
import os
import sys
import bisect
import heapq
import itertools
from functools import lru_cache
from typing import List
MAXN = 2 * 10 ** 5 + 5
parent = [i for i in range(MAXN)]

def find(u):
	pu = parent[u]
	if pu == u:
		return pu
	pu = find(pu)
	parent[u] = pu
	return pu

def merge(u, v):
	(pu, pv) = (find(u), find(v))
	parent[pu] = pv
	return pu != pv

def solve(n, m, k, edges):
	edges.sort()
	for i in range(n + 1):
		parent[i] = i
	groups = n
	ans = 0
	for (i, (s, u, v)) in enumerate(edges):
		if s <= k:
			if merge(u, v):
				groups -= 1
		else:
			if groups == 1:
				return min(k - edges[i - 1][0], s - k)
			if merge(u, v):
				groups -= 1
				ans += s - k
			if groups == 1:
				return ans
	return k - edges[-1][0]
T = int(input())
ans = []
for ti in range(T):
	(n, m, k) = map(int, input().strip().split())
	edges = []
	for _ in range(m):
		(u, v, s) = map(int, input().split())
		edges.append((s, u, v))
	ans.append(solve(n, m, k, edges))
print('\n'.join(map(str, ans)))


from sys import stdin, stdout

def road_reform(n, m, k, xys_a, d1):
	xys_a.sort(key=lambda x: x[2])
	ua = [i for i in range(0, n + 1)]
	res = 0
	d2 = 0
	for xys in xys_a:
		rx = ufind(ua, xys[0])
		ry = ufind(ua, xys[1])
		if rx != ry:
			union(ua, rx, ry)
			res += max(0, xys[2] - k)
			d2 = xys[2] - k
	if d2 < 0:
		if abs(d2) < d1:
			res = abs(d2)
		else:
			res = d1
	return res

def ufind(ua, i):
	if ua[i] != i:
		ua[i] = ufind(ua, ua[i])
	return ua[i]

def union(ua, i, j):
	ri = ufind(ua, i)
	rj = ufind(ua, j)
	ua[ri] = rj
t = int(stdin.readline())
for _ in range(t):
	(n, m, k) = map(int, stdin.readline().split())
	xys_a = []
	d1 = 10 ** 9
	for _ in range(m):
		(x, y, s) = map(int, stdin.readline().split())
		xys_a.append([x, y, s])
		d1 = min(d1, abs(k - s))
	res = road_reform(n, m, k, xys_a, d1)
	stdout.write(str(res) + '\n')


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=300006, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.height = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val == 0:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
			elif val >= 1:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left

	def do(self, temp):
		if not temp:
			return 0
		ter = temp
		temp.height = self.do(ter.left) + self.do(ter.right)
		if temp.height == 0:
			temp.height += 1
		return temp.height

	def query(self, xor):
		self.temp = self.root
		cur = 0
		i = 31
		while i > -1:
			val = xor & 1 << i
			if not self.temp:
				return cur
			if val >= 1:
				self.opp = self.temp.right
				if self.temp.left:
					self.temp = self.temp.left
				else:
					return cur
			else:
				self.opp = self.temp.left
				if self.temp.right:
					self.temp = self.temp.right
				else:
					return cur
			if self.temp.height == pow(2, i):
				cur += 1 << i
				self.temp = self.opp
			i -= 1
		return cur
for ik in range(int(input())):
	(n, m, k) = map(int, input().split())
	p = [i for i in range(n + 1)]

	def get(a):
		if p[a] != a:
			p[a] = get(p[a])
		return p[a]

	def union(a, b):
		a = get(a)
		b = get(b)
		p[a] = b
	da = []
	ans = 0
	ma = 0
	for i in range(m):
		(a, b, c) = map(int, input().split())
		if c <= k:
			union(a, b)
			ma = max(ma, c)
		else:
			da.append((c, a, b))
	da.sort()
	t = 0
	for i in range(len(da)):
		(c, a, b) = da[i]
		if get(a) != get(b):
			t = 1
			union(a, b)
			ans += abs(k - c)
	if t == 0:
		ans = abs(k - ma)
		if len(da) > 0:
			ans = min(da[0][0] - k, abs(k - ma))
	print(ans)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import sys
from collections import defaultdict

def merge(a, b):
	par[a] = b

def find(a):
	if par[a] == -1:
		return a
	stack = []
	while par[a] != -1:
		stack.append(a)
		a = par[a]
	while stack:
		par[stack.pop()] = a
	return a

def dfs(node):
	vis[node] = 1
	stack = [node]
	ans = 0
	while stack:
		cur = stack.pop()
		ans += 1
		for j in edge2[cur]:
			if vis[j[0]] == 0:
				vis[j[0]] = 1
				stack.append(j[0])
	return ans
t = int(input())
for _ in range(t):
	(n, m, k) = list(map(int, input().split()))
	lis = []
	edge2 = defaultdict(list)
	arr = []
	for i in range(m):
		(u, v, x) = list(map(int, input().split()))
		arr.append([u, v, x])
		if x <= k:
			edge2[u].append([v, x])
			edge2[v].append([u, x])
			lis.append(x)
	vis = [0] * (n + 1)
	a = dfs(1)
	if a == n:
		ans = sys.maxsize
		for i in range(m):
			ans = min(ans, abs(k - arr[i][2]))
		print(ans)
	else:
		y = 0
		z = 0
		par = [-1] * (n + 1)
		arr.sort(key=lambda x: x[2], reverse=False)
		ans = 0
		for i in range(m):
			a = find(arr[i][0])
			b = find(arr[i][1])
			if a != b:
				ans += arr[i][2]
				merge(a, b)
				if arr[i][2] > k:
					z += 1
				else:
					y += arr[i][2]
		print(ans - y - z * k)


from sys import stdin, stdout
import heapq
t = int(stdin.readline())

def parent(x, parents):
	changes = []
	while parents[x] != x:
		changes.append(x)
		x = parents[x]
	for y in changes:
		parents[y] = x
	return x
for case in range(t):
	(n, m, k) = [int(x) for x in stdin.readline().split()]
	edges = []
	for r in range(m):
		(x, y, s) = [int(x) for x in stdin.readline().split()]
		edges.append((s, x, y))
	edges.sort()
	new = []
	parents = [a for a in range(n + 1)]
	for (s, x, y) in edges:
		if parent(x, parents) == parent(y, parents):
			continue
		else:
			parents[max(parents[x], parents[y])] = min(parents[x], parents[y])
			new.append((s, x, y))
			if len(new) == n - 1:
				break
	if new[-1][0] >= k:
		total = 0
		for x in new:
			total += max(0, x[0] - k)
		print(total)
	else:
		print(min([abs(k - a[0]) for a in edges]))


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):

	def __init__(self, file):
		self.newlines = 0
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline()

def RL():
	return map(int, sys.stdin.readline().split())

def RLL():
	return list(map(int, sys.stdin.readline().split()))

def N():
	return int(input())

def S():
	return input().strip()

def print_list(l):
	print(' '.join(map(str, l)))

class DSU:

	def __init__(self, n):
		self.uf = {i: i for i in range(n)}
		self.rank = {i: 1 for i in range(n)}

	def find(self, x):
		if self.uf[x] != x:
			self.uf[x] = self.find(self.uf[x])
		return self.uf[x]

	def union(self, x, y):
		(px, py) = (self.find(x), self.find(y))
		if px != py:
			if self.rank[px] > self.rank[py]:
				(px, py) = (py, px)
			self.rank[py] += self.rank[px]
			self.uf[px] = py
			return True
		return False
for _ in range(N()):
	(n, m, k) = RL()
	edges = sorted([RLL() for _ in range(m)], key=lambda x: x[2])
	dsu = DSU(n)
	ans = 0
	for (x, y, t) in edges:
		if dsu.union(x - 1, y - 1):
			ans += max(0, t - k)
	if ans <= 0:
		ans = min((abs(p[2] - k) for p in edges))
	print(ans)


import sys

def load_sys():
	return sys.stdin.readlines()

def load_local():
	with open('input.txt', 'r') as f:
		input = f.readlines()
	return input

def f(n, m, k, edges):
	edges.sort(key=lambda x: x[-1])
	UF = {x: x for x in range(1, n + 1)}

	def find(x):
		if UF[x] != x:
			UF[x] = find(UF[x])
		return UF[x]

	def union(x, y):
		UF[find(y)] = find(x)
		return
	edges_cnt = 0
	ans = 0
	for (idx, (i, j, w)) in enumerate(edges):
		if w < k:
			if find(i) != find(j):
				union(i, j)
				edges_cnt += 1
		else:
			if edges_cnt >= n - 1:
				return min(w - k, k - edges[idx - 1][-1])
			if find(i) != find(j):
				union(i, j)
				edges_cnt += 1
				ans += w - k
			if edges_cnt >= n - 1:
				return ans
	return k - w
input = load_sys()
i = 1
while i < len(input):
	(n, m, k) = map(int, input[i].split())
	edges = []
	for _ in range(m):
		i += 1
		(x, y, w) = map(int, input[i].split())
		edges.append((x, y, w))
	i += 1
	print(f(n, m, k, edges))


from sys import stdin, stdout
from math import gcd, sqrt, factorial, pi, inf
from collections import deque, defaultdict
from bisect import bisect, bisect_left
from time import time
from itertools import permutations as per
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\r\n')
L = lambda : list(R())
P = lambda x: stdout.write(str(x) + '\n')
lcm = lambda x, y: x * y // gcd(x, y)
nCr = lambda x, y: f[x] * inv(f[y] * f[x - y] % N) % N
inv = lambda x: pow(x, N - 2, N)
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7

def dsu(x):
	p = x
	while v[x] != x:
		x = v[x]
	v[p] = x
	return x
for _ in range(I()):
	(n, m, k) = R()
	g = sorted([L() for i in range(m)], key=lambda x: x[-1])
	v = [i for i in range(n + 1)]
	d = inf
	ans = 0
	for (a, b, s) in g:
		p = dsu(a)
		q = dsu(b)
		d = min(d, abs(s - k))
		if p != q:
			v[p] = v[q]
			ans += max(0, s - k)
	print(ans if ans else d)


from collections import defaultdict

class DisjointSet:

	def __init__(self, element_num=None):
		self._father = {}
		self._rank = {}
		if element_num is not None:
			for i in range(element_num):
				self.add(i)

	def add(self, x):
		if x in self._father:
			return
		self._father[x] = x
		self._rank[x] = 0

	def _query(self, x):
		if self._father[x] == x:
			return x
		self._father[x] = self._query(self._father[x])
		return self._father[x]

	def merge(self, x, y):
		if x not in self._father:
			self.add(x)
		if y not in self._father:
			self.add(y)
		x = self._query(x)
		y = self._query(y)
		if x == y:
			return
		if self._rank[x] < self._rank[y]:
			self._father[x] = y
		else:
			self._father[y] = x
			if self._rank[x] == self._rank[y]:
				self._rank[x] += 1

	def same(self, x, y):
		return self._query(x) == self._query(y)
t = int(input())
for z in range(t):
	(n, m, k) = list(map(int, input().split(' ')))
	edges = []
	for i in range(m):
		(u, v, s) = list(map(int, input().split(' ')))
		edges.append((u, v, s))
	ret = 0
	cur = 1000000000.0
	dset = DisjointSet(n + 1)
	edges = sorted(edges, key=lambda x: x[2])
	used = defaultdict(bool)
	for (i, e) in enumerate(edges):
		if dset.same(e[0], e[1]):
			continue
		else:
			dset.merge(e[0], e[1])
			ret += max(0, e[2] - k)
			cur = min(cur, abs(e[2] - k))
			used[i] = True
	if ret > 0:
		print(ret)
		continue
	else:
		for (i, e) in enumerate(edges):
			if used[i] or abs(e[2] - k) > cur:
				continue
			cur = abs(e[2] - k)
		print(cur)


from collections import defaultdict, deque
import sys
import bisect
import math
input = sys.stdin.readline
mod = 1000000007

def get(a):
	if p[a] != a:
		p[a] = get(p[a])
	return p[a]

def union(a, b):
	a = get(a)
	b = get(b)
	p[a] = b
t = int(input())
for ii in range(t):
	(n, m, k) = map(int, input().split())
	p = [int(i) for i in range(n + 1)]
	great = []
	ans = 0
	maxa = 0
	for i in range(m):
		(a, b, c) = map(int, input().split())
		if c <= k:
			union(a, b)
			maxa = max(maxa, c)
		else:
			great.append((c, a, b))
	great.sort()
	ok = True
	for i in range(len(great)):
		if get(great[i][1]) != get(great[i][2]):
			ok = False
			union(great[i][1], great[i][2])
			ans += great[i][0] - k
	if ok:
		ans = abs(k - maxa)
		if len(great) > 0:
			ans = min(great[0][0] - k, k - maxa)
	print(ans)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
from heapq import *
from math import gcd, factorial, floor, ceil, sqrt
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def testcase(t):
	for pp in range(t):
		solve(pp)

def google(p):
	print('Case #' + str(p) + ': ', end='')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(x, y, p):
	y %= p - 1
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True
inf = pow(10, 20)
mod = 10 ** 9 + 7

class UnionFind:

	def __init__(self, n):
		self.parent = list(range(n))

	def find(self, a):
		acopy = a
		while a != self.parent[a]:
			a = self.parent[a]
		while acopy != a:
			(self.parent[acopy], acopy) = (a, self.parent[acopy])
		return a

	def merge(self, a, b):
		self.parent[self.find(b)] = self.find(a)

def kruskal(n, U, V, W):
	union = UnionFind(n)
	(cost, merge_cnt) = (0, 0)
	(mst_u, mst_v) = ([], [])
	order = sorted(range(len(W)), key=lambda x: W[x])
	taken = []
	for i in range(len(W)):
		(u, v) = (U[order[i]], V[order[i]])
		(find_u, find_v) = (union.find(u), union.find(v))
		if find_u != find_v:
			cost += W[order[i]]
			merge_cnt += 1
			union.parent[find_v] = find_u
			(mst_u.append(u), mst_v.append(v))
			taken.append(order[i])
		if merge_cnt == n - 1:
			break
	return taken

def solve(case):
	(n, m, k) = sep()
	u = []
	v = []
	w = []
	for i in range(m):
		(a, b, c) = sep()
		a -= 1
		b -= 1
		u.append(a)
		v.append(b)
		w.append(c)
	ans = 0
	f = True
	taken = kruskal(n, u, v, w)
	currmax = -inf
	have = set()
	for i in taken:
		have.add(i)
		currmax = max(currmax, w[i])
		if w[i] >= k:
			f = False
			ans += abs(k - w[i])
	if f:
		ans = abs(k - currmax)
		for i in range(m):
			if i in have:
				continue
			if w[i] > currmax:
				ans = min(ans, abs(k - w[i]))
		print(ans)
	else:
		print(ans)
testcase(int(inp()))


import sys

def generate_testcase():
	import random
	with open('in.txt', 'w') as f:
		print(1, file=f)
		print(200000, 200000, 500000, file=f)
		data = [(i, i + 1, random.randint(1, 1000000)) for i in range(1, 200000)] + [(96012, 176243, random.randint(1, 1000000))]
		random.shuffle(data)
		for row in data:
			print(*row, file=f)

def main(input_fcn=sys.stdin.readline):
	for _ in range(int(input_fcn())):
		(n, m, k) = map(int, input_fcn().split())
		roads0 = [(0, 0)] * m
		m0 = 0
		roads1 = [(0, 0, 0)] * m
		m1 = 0
		for _ in range(m):
			(s, d, lim) = map(int, input_fcn().split())
			if lim > k:
				roads1[m1] = (lim - k, s, d)
				m1 += 1
			else:
				roads0[m0] = (k - lim, s, d)
				m0 += 1
		roads1 = sorted(roads1[:m1])
		res = 0
		parent = [i for i in range(n + 1)]
		for i in range(m0):
			(_, s, d) = roads0[i]
			(ps, pd) = (s, d)
			while parent[ps] != ps:
				ps = parent[ps]
			while parent[pd] != pd:
				pd = parent[pd]
			if ps != pd:
				parent[s] = ps
				parent[d] = ps
				parent[pd] = ps
			else:
				parent[s] = ps
				parent[d] = ps
		for i in range(m1):
			(mod, s, d) = roads1[i]
			(ps, pd) = (s, d)
			while parent[ps] != ps:
				ps = parent[ps]
			while parent[pd] != pd:
				pd = parent[pd]
			if ps != pd:
				res += mod
				parent[s] = ps
				parent[d] = ps
				parent[pd] = ps
			else:
				parent[s] = ps
				parent[d] = ps
		if not res:
			if roads0:
				corr = min((roads0[i][0] for i in range(m0)))
			else:
				corr = 1e+30
			if roads1:
				corr = min(corr, roads1[0][0])
			res += int(corr)
		print(res)
main()