# 2020 USACO January Silver

# 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 **n** cows, 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`

. But this morning there are also _{i}**m** wormholes, numbered **1**...**m**, where wormhole **i** bidirectionally connects location `a`

with location _{i}`b`

, and has a width _{i}`w`

._{i}

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.

#### Input

The first line contains two integers **n** (**1** ≤ **n** ≤ `10`

) and ^{5}**m** (**1** ≤ **m** ≤ `10`

). The second line contains the ^{5}**n** integers `p`

, _{1}`p`

,..., _{2}`p`

. It is guaranteed that _{n}**p** is a permutation of **1**...**n**.

For each **i** between **1** and **m**, line **i** + **2** contains the integers `a`

, _{i}`b`

and _{i}`w`

(_{i}**1** ≤ `a`

, _{i}`b`

≤ _{i}**n**, `a`

≠ _{i}`b`

, _{i}**1** ≤ `w`

≤ _{i}`10`

).^{9}

#### Output

Print 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**.

#### Example

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.

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