#U1920JS3. Wormhole Sort
Wormhole Sort
Farmer 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 NN cows (1≤N≤1051≤N≤105), conveniently numbered 1…N1…N, are scattered throughout the barn at NN distinct locations, also numbered 1…N1…N, such that cow ii is at location pipi. But this morning there are also MM wormholes (1≤M≤1051≤M≤105), numbered 1…M1…M, where wormhole ii bidirectionally connects location aiai with location bibi, and has a width wiwi (1≤ai**,bi≤N**,ai≠bi,1≤wi≤1091≤ai,bi≤N,ai≠bi,1≤wi≤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 ii is at location ii for 1≤i≤N1≤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.
SCORING:
- Test cases 3-5 satisfy N,M≤**1000.**N,M≤1000.
- Test cases 6-10 satisfy no additional constraints.
INPUT FORMAT (file wormsort.in):
The first line contains two integers, NN and MM.The second line contains the NN integers p1**,p2**,…,pNp1,p2,…,pN. It is guaranteed that pp is a permutation of 1…N.1…N.
For each ii between 11 and MM, line i+2i+2 contains the integers aiai, bibi, and wiwi.
OUTPUT FORMAT (file wormsort.out):
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−1.
SAMPLE INPUT:
4 4
3 2 1 4
1 2 9
1 3 7
2 3 10
2 4 3
SAMPLE OUTPUT:
9
Here is one possible way to sort the cows using only wormholes of width at least 9:
- Cow 1 and cow 2 swap positions using the third wormhole.
- Cow 1 and cow 3 swap positions using the first wormhole.
- Cow 2 and cow 3 swap positions using the third wormhole.
SAMPLE INPUT:
4 1
1 2 3 4
4 2 13
SAMPLE OUTPUT:
-1
No wormholes are needed to sort the cows.