Under construction

Still being built. Things may change

Two Captains

Time limit3sMemory limit1024 MB

Summary
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 nn 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 ll rr: sends their crew to fire the cannons numbered from ll to rr inclusive
  • back ll rr: recalls all of their crew from the cannons numbered from ll to rr inclusive. Cannons in this range that have no crew loyal to this captain are left unchanged
  • rum: 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 m1m_1 commands, and Barbossa's plan has m2m_2 commands. At the start of minute ii, each captain gives his crew the ii-th command from his plan, if the plan has at least ii 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 nn, the number of cannons (1≤n≤1091 \le n \le 10^9).

The second line contains m1m_1, the number of commands in Jack Sparrow's plan (1≤m1≤30001 \le m_1 \le 3000). The next m1m_1 lines list the commands in that plan, in the format described above. For every command using ll and rr, 1≤l≤r≤n1 \le l \le r \le n holds. The last command in the plan is back 1 nn.

The next line contains m2m_2, the number of commands in Barbossa's plan (1≤m2≤30001 \le m_2 \le 3000). The next m2m_2 lines list the commands in that plan, with the same constraints. The last command in the plan is back 1 nn.

Output

Print one line with the minimum number of additional commands.

Examples1

  1. Example 1

    Input
    3
    4
    send 1 1
    send 2 2
    back 1 1
    back 1 3
    5
    send 2 3
    send 1 1
    back 2 2
    rum
    back 1 3
    
    Expected output
    3