IOIOI Cards
Time limit1sMemory limit512 MB
Given a row of I/O cards and interval flip operations with per-length costs, decide whether all cards can be turned face up and find the minimum total flip time.
- Level
Hard8 of 10
- Topics
- Shortest path, Graph, Math, Prefix sum
- Solved
- No attempts yet
Problem
Chairman K enjoys fortune telling and practices many forms of it. Today he decided to use cards with 'I' on the front and 'O' on the back to tell the fortunes of the Japanese team at this year's IOI.
The fortune telling works as follows.
- First, choose positive integers .
- Lay out cards in a single row. The leftmost cards are face up, the next cards are face down, the next cards are face up, the next cards are face down, and the next cards are face up. Laid out this way, the row shows copies of 'I', then copies of 'O', then copies of 'I', then copies of 'O', then copies of 'I', from left to right.
- Choose one or more of the predetermined operations and perform them in any order. The same operation may be performed more than once. Operation () is "flip every card from the -th to the -th position from the left." Flipping one card takes 1 second, so performing operation takes seconds.
- If every card is face up after all operations, the fortune telling succeeds.
To avoid flipping cards more than necessary, Chairman K decided to first determine whether the fortune telling can succeed before actually using the cards. Moreover, if it can succeed, he decided to find the minimum time needed to make it succeed.
Given the information about how the cards are laid out and the predetermined operations, write a program that determines whether the fortune telling can succeed and, if so, finds the minimum time needed to make it succeed.
Input
Read the following data from standard input.
- The first line contains integers separated by spaces. This means that at the start of the fortune telling, cards are laid out so that the leftmost are face up, the next are face down, the next are face up, the next are face down, and the next are face up.
- The second line contains the integer . This means there are predetermined operations.
- Of the following lines, the -th line () contains integers separated by spaces. This means that operation is "flip every card from the -th to the -th position from the left."
Output
If the fortune telling can succeed, print a single line to standard output containing the integer that is the minimum time needed to make it succeed. Otherwise, print .
Constraints
- .
- .
- .
- .
- .
- .
- ().