atcoder#ABC271E. [ABC271E] Subsequence Path
[ABC271E] Subsequence Path
Score : points
Problem Statement
There are towns numbered , and roads numbered . Every road is directed; road leads you from Town to Town . The length of road is .
You are given a sequence of length consisting of integers between and . A way of traveling from town to town using roads is called a good path if:
- the sequence of the roads' numbers arranged in the order used in the path is a subsequence of .
Note that a subsequence of a sequence is a sequence obtained by removing or more elements from the original sequence and concatenating the remaining elements without changing the order.
Find the minimum sum of the lengths of the roads used in a good path. If there is no good path, report that fact.
Constraints
- $1 \leq A_i, B_i \leq N, A_i \neq B_i \, (1 \leq i \leq M)$
- All values in the input are integers.
Input
The input is given from Standard Input in the following format:
Output
Find the minimum sum of the lengths of the roads used in a good path.
If there is no good path, print -1
.
3 4 4
1 2 2
2 3 2
1 3 3
1 3 5
4 2 1 2
4
There are two possible good paths as follows:
- Using road . In this case, the sum of the length of the used road is .
- Using road and in this order. In this case, the sum of the lengths of the used roads is .
Therefore, the desired minimum value is .
3 2 3
1 2 1
2 3 1
2 1 1
-1
There is no good path.
4 4 5
3 2 2
1 3 5
2 4 7
3 4 10
2 4 1 4 3
14