#P6004. [USACO20JAN] Wormhole Sort S
[USACO20JAN] Wormhole Sort S
Description
Farmer John’s cows are tired of his daily demand that they leave the barn sorted every morning. They have just finished PhDs in quantum physics and are ready to speed this process up.
This morning, as usual, Farmer John’s cows numbered () are spread across distinct positions in the barn, also numbered . Cow is currently at position . However, this morning there are also wormholes numbered (). Wormhole connects positions and in both directions, and has width ().
At any time, two cows located at the two ends of a wormhole may choose to swap positions through the wormhole. The cows need to repeat such swaps until for all , cow is at position .
The cows do not want to be squeezed by narrow wormholes. Help them maximize the minimum wormhole width among the wormholes they use during the sorting process. It is guaranteed that the cows can be sorted.
Input Format
The first line contains two integers and .
The second line contains integers . It is guaranteed that is a permutation of .
For each from to , line contains integers .
Output Format
Output one integer: the maximum possible value of the minimum width of any wormhole that the cows must squeeze into during the sorting process. If the cows do not need to use any wormholes to sort, output .
4 4
3 2 1 4
1 2 9
1 3 7
2 3 10
2 4 3
9
4 1
1 2 3 4
4 2 13
-1
Hint
Sample Explanation 1
Here is one possible way to sort the cows using only wormholes of width at least :
- 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.
Subtasks
- Test cases satisfy .
- Test cases have no additional constraints.
Translated by ChatGPT 5
京公网安备 11011102002149号