This page is still under construction.

Parts of this page are still being built. What you see may change.

Sequence Walking

Time limit1sMemory limit128 MB

Summary
Given two ascending integer sequences, find the maximum sum of a forward walk that may switch sequences at shared values.
Level

Medium5 of 10

Topics
Dynamic programming, Two pointers
Solved
No attempts yet

Problem

Two finite integer sequences sorted in ascending order are given. A value contained in both sequences can be regarded as a crossing point where the two sequences meet.

The two sequences are shown below, with the crossing points in bold.

  • Sequence 1 = 3 5 7 9 20 25 30 40 55 56 57 60 62
  • Sequence 2 = 1 4 7 11 14 25 44 47 55 57 100

You walk along these two sequences under the following rules.

  1. Start at the first element of one of the two sequences. You may only move forward (toward larger values).
  2. Whenever you reach a crossing point, you may either keep following the current sequence or switch to the other sequence.
  3. The walk ends when there is no next element to move to, that is, when you reach the last element of the sequence you are currently on.

Find the maximum possible sum of all elements visited along such a walk. For example, walking 3, 5, 7, 9, 20, 25, 44, 47, 55, 56, 57, 60, 62 over the two sequences above gives a sum of 450, which is the maximum attainable.

Input

The input consists of several test cases. Each test case is given on two lines, one line per sequence.

Each line begins with the length LL of the sequence, followed by its LL integers in ascending order, separated by spaces. The length satisfies 1≤L≤100001 \le L \le 10000, and every element is an integer with −10000≤ai≤10000-10000 \le a_i \le 10000.

The last line of the input contains a single 00, which marks the end of the input.

Output

For each test case, print the maximum obtainable sum on its own line.

Examples1

  1. Example 1

    Input
    13 3 5 7 9 20 25 30 40 55 56 57 60 62
    11 1 4 7 11 14 25 44 47 55 57 100
    4 -5 100 1000 1005
    3 -12 1000 1001
    0
    
    Expected output
    450
    2100