## WC '17 Contest 4 S2 - Strange Travels

View as PDF

Points: 12 (partial)
Time limit: 1.8s
Memory limit: 64M

Author:
Problem type
##### Woburn Challenge 2017-18 Round 4 - Senior Division

Desperate to find more allies to join in the fight against Thanos, the Avengers have requested assistance from Doctor Strange, a powerful magician. Strange is willing to help, but he'll need some assistance of his own first. To fully apply his powers to the fight, he'll need to gather together a set of artifacts from hidden sanctums around the world!

There are sanctums, numbered from 1 to , spread out all across the Earth. It would take far too long to travel amongst them by conventional means, but Doctor Strange has access to a convenient alternative – magical portals. There are one-way portals, with the -th of them allowing for instantaneous travel from sanctum to . No two portals connect the same pair of sanctums in the same direction.

There are artifacts which Strange requires, with the -th of them being held in sanctum . No artifact is in sanctum , and no two artifacts are located in the same sanctum.

Doctor Strange is initially located in sanctum , also known as the Sanctum Sanctorum. He'll need to recover all artifacts back to the Sanctum Sanctorum, one by one. In particular, for each artifact in order, he'll need to warp through a sequence of or more portals to reach sanctum , collect the artifact, and then warp through a sequence of or more portals to return to sanctum before heading back out for the next one. Note that he may not carry multiple artifacts at a time, and must collect the artifacts in order. Overall, he'll be required to visit the following sequence of sanctums:

Determine the minimum number of portal warps which Doctor Strange will need to perform to achieve his goal. Unfortunately, it may instead turn out to be impossible to visit the entire required sequence of sanctums, in which case you should output -1 instead.

In test cases worth of the points, and .
In test cases worth another of the points, and .

#### Input Specification

The first line of input consists of two space-separated integers, and .
lines follow, the -th of which consists of two space-separated integers, and , for .
The next line consists of integers, .

#### Output Specification

Output a single integer, either the minimum number of warps required to recover all of the artifacts, or -1 if not all of them can be recovered.

#### Sample Input 1

4 6
1 2
2 3
3 1
1 3
4 3
3 4
2
4 2

#### Sample Output 1

7

#### Sample Input 2

4 5
1 2
3 1
1 3
4 3
3 4
2
4 2

#### Sample Output 2

-1

#### Sample Explanations

In the first case, Doctor Strange can warp through the following sequence of sanctums:

In the second case, Doctor Strange would be able to recover the first artifact and then reach the second one, but he would then be unable to return to sanctum with it.