atcoder#AGC062B. [AGC062B] Split and Insert
[AGC062B] Split and Insert
[English Translation]
Score : points
Problem Statement
There is a permutation of the integers from to . Initially, we have .
Takahashi will perform the following operation on this sequence times.
- Choose an integer such that . Take the last terms of and insert them among the first . More precisely, replace with any permutation of the integers that satisfies the following conditions.- is a (not necessarily contiguous) subsequence of .
- is a (not necessarily contiguous) subsequence of .
- is a (not necessarily contiguous) subsequence of .
- is a (not necessarily contiguous) subsequence of .
The cost of the series of operations is , where is the chosen in the -th operation.
Takahashi wants to perform operations so that afterward.
Determine whether it is possible to perform such a series of operations. If it is possible, find its minimum cost.
Constraints
- is a permutation of the integers from to .
- All input values are integers.
Input
The input is given from Standard Input in the following format:
Output
If it is impossible to perform operations so that holds afterward, print -1
. If it is possible, print the minimum cost of such a series of operations.
4 1
3
3 1 2 4
6
By choosing , and inserting before and after , we can make , which satisfies . The cost of this operation is .
It can be proved that the minimum cost of performing operations so that afterward is .
4 1
3
4 3 2 1
-1
It is impossible to perform operations so that afterward.
20 10
874735445 684260477 689935252 116941558 915603029 923404262 843759669 656978932 286318130 255195090
11 15 20 10 6 8 18 2 12 4 9 13 19 3 16 7 14 17 5 1
7372920743