A Slightly Slow but Kind Friend
InterviewTime limit1sMemory limit512 MB
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 neighborhoods around Gyeongsang National University, numbered 1 to . For convenience, Bosun treats the university as point . 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 one-way roads, each connecting two different points among the university and the 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 and , separated by a space.
The second line contains , separated by spaces. This means the sky photo of neighborhood must be taken later than the sky photo of neighborhood . If , the time of the photo in neighborhood can be anything.
From the third line onward, lines each give a one-way road , , , separated by spaces. The -th road starts at , ends at , and takes time to traverse. Points to are the neighborhoods, and point is the university.
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.