PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#BS0000441. Sắp xếp bò qua lỗ sâu (Wormhole Sort)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Sắp xếp bò qua lỗ sâu (Wormhole Sort)

Wormhole Sort

Source: USACO

Version: Phuoc Hung OJ Extended

Problem Statement

Farmer John's barn has NN cows and NN locations, each numbered from 11 to NN. Cow ii starts at location pip_i, with exactly one cow at each location.

There are MM bidirectional wormholes. Wormhole jj links locations aja_j and bjb_j and has width wjw_j. Cows at its two endpoints may exchange locations. Exchanges may be repeated in any order.

Place cow ii at location ii for every ii. Among all sorting sequences, maximize the minimum width of the wormholes used. If no exchange is necessary, the result is -1. A sorting sequence always exists.

Input

  • The first line contains integers N,MN,M, the numbers of cows and wormholes.
  • The second line contains NN integers p1,p2,…,pNp_1,p_2,\ldots,p_N, where pip_i is cow ii's initial location.
  • Each of the next MM lines contains integers aj,bj,wja_j,b_j,w_j, the endpoints and width of wormhole jj.

Output

Print one integer: the maximum achievable minimum width, or -1 if pi=ip_i=i for every ii.

Subtasks

  • Subtask 1 (40 points): 1≤N,M≤10001\le N,M\le1000; pp is a permutation of 1,…,N1,\ldots,N; 1≤aj,bj≤N1\le a_j,b_j\le N, aj≠bja_j\ne b_j, 1≤wj≤1091\le w_j\le10^9 for every 1≤j≤M1\le j\le M. Sorting is possible.
  • Subtask 2 (60 points): 1≤N,M≤1000001\le N,M\le100000; pp is a permutation of 1,…,N1,\ldots,N; 1≤aj,bj≤N1\le a_j,b_j\le N, aj≠bja_j\ne b_j, 1≤wj≤1091\le w_j\le10^9 for every 1≤j≤M1\le j\le M. Sorting is possible.

Examples

Example 1

Input

4 4
3 2 1 4
1 2 9
1 3 7
2 3 10
2 4 3

Output

9

Explanation

Cow 1 is at location 3 and cow 3 at location 1. Exchange locations (2,3), (1,2), (2,3), using widths 10, 9, 10. All cows reach their destinations. With widths above 9, location 1 is isolated, making sorting impossible.

Example 2

Input

4 1
1 2 3 4
4 2 13

Output

-1

Explanation

All four cows are already correctly placed; no wormhole is needed.