#abc190e. [abc190_e]Magical Ornament
[abc190_e]Magical Ornament
Problem Statement
There are kinds of magical gems, numbered , distributed in the AtCoder Kingdom.
Takahashi is trying to make an ornament by arranging gems in a row.
For some pairs of gems, we can put the two gems next to each other; for other pairs, we cannot. We have pairs for which the two gems can be adjacent: (Gem , Gem ), (Gem , Gem ), , (Gem , Gem ). For the other pairs, the two gems cannot be adjacent. (Order does not matter in these pairs.)
Determine whether it is possible to form a sequence of gems that has one or more gems of each of the kinds . If the answer is yes, find the minimum number of stones needed to form such a sequence.
Constraints
- All values in input are integers.
- If , .
Input
Input is given from Standard Input in the following format:
Output
Print the minimum number of stones needed to form a sequence of gems that has one or more gems of each of the kinds .
If such a sequence cannot be formed, print -1
instead.
Sample Input 1
4 3
1 4
2 4
3 4
3
1 2 3
Sample Output 1
5
For example, by arranging the gems in the order \[1, 4, 2, 4, 3\], we can form a sequence of length with Gems .
Sample Input 2
4 3
1 4
2 4
1 2
3
1 2 3
Sample Output 2
-1
Sample Input 3
10 10
3 9
3 8
8 10
2 10
5 8
6 8
5 7
6 7
1 6
2 4
4
1 2 7 9
Sample Output 3
11
For example, by arranging the gems in the order \[1, 6, 7, 5, 8, 3, 9, 3, 8, 10, 2\], we can form a sequence of length with Gems .