The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.

In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.

Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.

Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.

Input

The first line contains two integers N (1 ≤ N ≤ 10^4) - number of airports/factories, and M (1 ≤ M ≤ 10^5) - number of available pairs to build a road between.

On next M lines, there are three integers u, v (1 ≤ u,v ≤ N), d (1 ≤ d ≤ 10^9) - meaning that you can build a road between airport u and factory v for d days.

Output

If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.

Example

Input


3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5


Output


4

Source: codeforces | Difficulty: HARD
Tags: Sorting

Graph algorithms

Flows and cuts


Solutions:
def hopcroft_karp(graph, n, m):
	assert n == len(graph)
	match1 = [-1] * n
	match2 = [-1] * m
	for node in range(n):
		for nei in graph[node]:
			if match2[nei] == -1:
				match1[node] = nei
				match2[nei] = node
				break
	while 1:
		bfs = [node for node in range(n) if match1[node] == -1]
		depth = [-1] * n
		for node in bfs:
			depth[node] = 0
		for node in bfs:
			for nei in graph[node]:
				next_node = match2[nei]
				if next_node == -1:
					break
				if depth[next_node] == -1:
					depth[next_node] = depth[node] + 1
					bfs.append(next_node)
			else:
				continue
			break
		else:
			break
		pointer = [len(c) for c in graph]
		dfs = [node for node in range(n) if depth[node] == 0]
		while dfs:
			node = dfs[-1]
			while pointer[node]:
				pointer[node] -= 1
				nei = graph[node][pointer[node]]
				next_node = match2[nei]
				if next_node == -1:
					while nei != -1:
						node = dfs.pop()
						(match2[nei], match1[node], nei) = (node, nei, match1[node])
					break
				elif depth[node] + 1 == depth[next_node]:
					dfs.append(next_node)
					break
			else:
				dfs.pop()
	return (match1, match2)

def getMatchCounts(roads, days, n):
	adj = [[] for _ in range(n)]
	for (u, v, d) in roads:
		if d <= days:
			adj[u].append(v)
	matchCounts = n - hopcroft_karp(adj, n, n)[0].count(-1)
	return matchCounts

def main():
	(n, m) = readIntArr()
	roads = []
	for _ in range(m):
		(u, v, d) = readIntArr()
		u -= 1
		v -= 1
		roads.append([u, v, d])
	if getMatchCounts(roads, 1000000000.0 + 1, n) < n:
		print(-1)
	else:
		days = 0
		b = 1000000000
		while b > 0:
			while getMatchCounts(roads, days + b, n) < n:
				days += b
			b //= 2
		days += 1
		print(days)
	return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(i, j):
	print('? {} {}'.format(i, j))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(' '.join([str(x) for x in ans])))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
for _abc in range(1):
	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 RL():
	return map(int, sys.stdin.readline().rstrip().split())

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

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

def print_list(l):
	print(' '.join(map(str, l)))
from collections import defaultdict as dc

def judge(last, key, d1, d2):
	if key > last:
		for (a, b, c) in data:
			if last < c <= key:
				d1[a].add(b)
				d2[b].add(a)
	else:
		for (a, b, c) in data:
			if key < c <= last:
				d1[a].remove(b)
				if not d1[a]:
					del d1[a]
				d2[b].remove(a)
				if not d2[b]:
					del d2[b]
	if len(d1.keys()) < n or len(d2.keys()) < n:
		return False
	for a in d1:
		lone = 0
		for b in d1[a]:
			if len(d2[b]) == 1:
				lone += 1
				if lone > 1:
					return False
	for b in d2:
		lone = 0
		for a in d2[b]:
			if len(d1[a]) == 1:
				lone += 1
				if lone > 1:
					return False
	used = set()
	for a in d1:
		if a not in used:
			(s1, s2, now) = ({a}, d1[a].copy(), d1[a].copy())
			while now:
				b = now.pop()
				da = d2[b] - s1
				s1 |= da
				for aa in da:
					db = d1[aa] - s2
					now |= db
					s2 |= db
			if len(s1) != len(s2):
				return False
			used |= s1
	return True
(n, m) = RL()
data = []
for _ in range(m):
	data.append(tuple(map(int, sys.stdin.readline().split())))
(l, r) = (min((a[2] for a in data)), max((a[2] for a in data)) + 1)
md = r
last = 0
du = dc(set)
dv = dc(set)
while l < r:
	key = l + r >> 1
	if judge(last, key, du, dv):
		r = key
	else:
		l = key + 1
	last = key
if l >= md:
	print(-1)
else:
	print(l)


from sys import stdin, stdout
from collections import deque
import sys
graph = []
n = 0
current_graph = []
pair_f = []
pair_a = []
dist = []

def dfs(s):
	global pair_f
	global pair_a
	global dist
	if s != 0:
		for a in current_graph[s]:
			if dist[pair_a[a]] == dist[s] + 1:
				if dfs(pair_a[a]):
					pair_a[a] = s
					pair_f[s] = a
					return True
		dist[s] = 10 ** 4 + 1
		return False
	return True

def bfs():
	global dist
	q = deque()
	inf = 10 ** 4 + 1
	for f in range(1, n + 1):
		if pair_f[f] == 0:
			dist[f] = 0
			q.append(f)
		else:
			dist[f] = inf
	dist[0] = inf
	while q:
		f = q.popleft()
		if dist[f] < dist[0]:
			for a in current_graph[f]:
				if dist[pair_a[a]] == inf:
					dist[pair_a[a]] = dist[f] + 1
					q.append(pair_a[a])
	return dist[0] != inf

def HopcroftKarp():
	global pair_f
	global pair_a
	global dist
	match = 0
	pair_f = [0] * (n + 1)
	pair_a = [0] * (n + 1)
	dist = [-1] * (n + 1)
	while bfs():
		for f in range(1, n + 1):
			if pair_f[f] == 0:
				if dfs(f):
					match += 1
	return match

def valuable_paper(min_d, max_d):
	global current_graph
	last_md = 10 ** 9 + 1
	l = min_d
	r = max_d
	m = 0
	while l <= r:
		m = (l + r) // 2
		current_graph = [[] for i in range(n + 1)]
		for edge in graph:
			if edge[2] <= m:
				current_graph[edge[0]].append(edge[1])
		current_graph[0] = [0]
		matchings = HopcroftKarp()
		if matchings == n:
			last_md = m
			r = m - 1
		else:
			l = m + 1
	if last_md == 10 ** 9 + 1:
		return -1
	else:
		return last_md

def main_method():
	global graph
	global n
	(n, m) = map(int, stdin.readline().split())
	graph = []
	for _ in range(m):
		(u, v, d) = map(int, stdin.readline().split())
		graph.append((u, v, d))
	min_d = min(graph, key=lambda e: e[2])[2]
	max_d = max(graph, key=lambda e: e[2])[2]
	sol = valuable_paper(min_d, max_d)
	stdout.write('{}\n'.format(sol))
main_method()