Under construction

Still being built. Things may change

A Slightly Slow but Kind Friend

Interview

Time limit1sMemory limit512 MB

Summary
Find the shortest route that leaves the university, visits each neighborhood once, and returns, while each photo follows its ordering constraint.
Level

Medium5 of 10

Topics
Dynamic programming, Bit manipulation, Shortest path
Solved
No attempts yet

Story

Bosun, who came to Jinju for an outing, found his classmate Wonwoo crying on a pond path near the front gate of Gyeongsang National University. Bosun walked over and asked why. Wonwoo explained through tears that the professor had sent him on an errand: start at Gyeongsang National University, visit every neighborhood around it to take sky photos, then return to the university. He could not refuse, but he did not know how to finish it. For the slightly slow but kind Wonwoo, Bosun decided to take over the errand.

Problem

There are NN neighborhoods around Gyeongsang National University, numbered 1 to NN. For convenience, Bosun treats the university as point N+1N+1. Each neighborhood can be visited only once. After leaving the university to take sky photos, he cannot return to it until all required photos are taken. There are MM one-way roads, each connecting two different points among the university and the NN neighborhoods. Two or more roads may have the same start and end points.

The professor gave one more instruction. Any two sky photos must be taken at different times, and the photo of a neighborhood must be taken later than the photo of the neighborhood assigned to it. Bosun wants to finish the errand as fast as possible. Ignore the time needed to take the photos. Find the minimum time to finish the errand.

Input

The first line contains NN and MM, separated by a space. (1≤N≤14;1≤M≤200)(1 \le N \le 14; 1 \le M \le 200)

The second line contains P1,…,PNP_1, \dots, P_N, separated by spaces. This means the sky photo of neighborhood ii must be taken later than the sky photo of neighborhood PiP_i. If i=Pii = P_i, the time of the photo in neighborhood ii can be anything. (1≤Pi≤N)(1 \le P_i \le N)

From the third line onward, MM lines each give a one-way road uiu_i, viv_i, wiw_i, separated by spaces. The ii-th road starts at uiu_i, ends at viv_i, and takes wiw_i time to traverse. Points 11 to NN are the neighborhoods, and point N+1N+1 is the university. (1≤ui,vi≤N+1;ui≠vi;1≤wi≤100)(1 \le u_i, v_i \le N+1; u_i \ne v_i; 1 \le w_i \le 100)

All numbers in the input are integers.

Output

Print the minimum time to finish the errand on the first line. If the errand cannot be finished, print -1.

Examples2

  1. Example 1

    Input
    2 6
    2 2
    3 1 1
    1 2 1
    2 3 1
    3 2 2
    2 1 2
    1 3 2
    
    Expected output
    6
    
  2. Example 2

    Input
    2 6
    2 1
    3 1 1
    1 2 1
    2 3 1
    3 2 2
    2 1 2
    1 3 2
    
    Expected output
    -1