Two Captains
Time limit3sMemory limit1024 MB
Given two command plans over n cannons, find the fewest rum commands to insert so no cannon ever holds crew from both captains.
- Level
Hard9 of 10
- Topics
- Dynamic programming, Simulation, Implementation
- Solved
- No attempts yet
Statement
The Black Pearl has two captains: Captain Jack Sparrow and Barbossa. The ship has exactly cannons arranged in a row. During a battle, both captains give commands to their crews at the same time once per minute. The commands are:
send: sends their crew to fire the cannons numbered from to inclusiveback: recalls all of their crew from the cannons numbered from to inclusive. Cannons in this range that have no crew loyal to this captain are left unchangedrum: brings one more bottle of rum
Each command is executed instantly, and then the battle continues for one minute until the next command. If at any moment crew members loyal to different captains are on the same cannon, they fight and kill each other. No captain wants this, so they asked you to help them fix the problem.
Before the battle, each captain made a plan of actions. Jack Sparrow's plan has commands, and Barbossa's plan has commands. At the start of minute , each captain gives his crew the -th command from his plan, if the plan has at least commands. You must fix the plans so that all crew members survive. The only change you can make is to insert several rum commands at any positions in the plans. Captains do not like changing their plans, so the total number of rum commands you add to both plans must be minimal.
Input
The first line contains , the number of cannons ().
The second line contains , the number of commands in Jack Sparrow's plan (). The next lines list the commands in that plan, in the format described above. For every command using and , holds. The last command in the plan is back 1 .
The next line contains , the number of commands in Barbossa's plan (). The next lines list the commands in that plan, with the same constraints. The last command in the plan is back 1 .
Output
Print one line with the minimum number of additional commands.