소가 놓인 위치의 순열과 너비가 있는 웜홀이 주어질 때, 모든 소를 제자리로 보내면서 사용하는 웜홀 너비의 최솟값을 최대로 만들고, 웜홀이 필요 없으면 -1을 출력한다.
어려움8유니온 파인드그래프정렬그리디아직 제출이 없습니다시간 제한2초메모리 제한512 MBFarmer John's cows have grown tired of his daily request that they sort themselves before leaving the barn each morning. They have just completed their PhDs in quantum physics, and are ready to speed things up a bit.
This morning, as usual, Farmer John's N cows (1≤N≤105), conveniently numbered 1…N, are scattered throughout the barn at N distinct locations, also numbered 1…N, such that cow i is at location p_i. But this morning there are also M wormholes (1≤M≤105), numbered 1…M, where wormhole i bidirectionally connects location a_i with location b_i, and has a width w_i (1≤a_i,b_i≤N,a_i=b_i,1≤w_i≤109).
At any point in time, two cows located at opposite ends of a wormhole may choose to simultaneously swap places through the wormhole. The cows must perform such swaps until cow i is at location i for 1≤i≤N.
The cows are not eager to get squished by the wormholes. Help them maximize the width of the least wide wormhole which they must use to sort themselves. It is guaranteed that it is possible for the cows to sort themselves.
The first line contains two integers, N and M.
The second line contains the N integers p_1,p_2,…,p_N. It is guaranteed that p is a permutation of 1…N.
For each i between 1 and M, line i+2 contains the integers a_i, b_i, and w_i.
A single integer: the maximum minimal wormhole width which a cow must squish itself into during the sorting process. If the cows do not need any wormholes to sort themselves, output −1.