#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 NN cows numbered 1N1 \ldots N (1N1051 \leq N \leq 10^5) are spread across NN distinct positions in the barn, also numbered 1N1 \ldots N. Cow ii is currently at position pip_i. However, this morning there are also MM wormholes numbered 1M1 \ldots M (1M1051 \leq M \leq 10^5). Wormhole ii connects positions aia_i and bib_i in both directions, and has width wiw_i (1ai,biN,aibi,1wi1091\le a_i,b_i\le N, a_i\neq b_i, 1\le w_i\le 10^9).

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 1iN1 \leq i \leq N, cow ii is at position ii.

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 NN and MM.

The second line contains NN integers p1,p2,,pNp_1,p_2,\ldots ,p_N. It is guaranteed that pp is a permutation of 1N1 \ldots N.

For each ii from 11 to MM, line i+2i+2 contains integers ai,bi,wia_i,b_i,w_i.

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 1-1.

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 99:

  • 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 353 \sim 5 satisfy N,M1000N,M \leq 1000.
  • Test cases 6106 \sim 10 have no additional constraints.

Translated by ChatGPT 5