ANARC05B - The Double HeLiX


Two finite, strictly increasing, integer sequences are given. Any common integer between the two sequences constitute an intersection point. Take for example the following two sequences where intersection points are
printed in bold:

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

You can ‘walk” over these two sequences in the following way:

  1. You may start at the beginning of any of the two sequences. Now start moving forward.
  2. At each intersection point, you have the choice of either continuing with the same sequence you’re currently on, or switching to the other sequence.

The objective is finding a path that produces the maximum sum of data you walked over. In the above example, the largest possible sum is 450, which is the result of adding 3, 5, 7, 9, 20, 25, 44, 47, 55, 56, 57, 60, and 62

Input

Your program will be tested on a number of test cases. Each test case will be specified on two separate lines. Each line denotes a sequence and is specified using the following format:

n v1 v2 ... vn

Where n is the length of the sequence and vi is the ith element in that sequence. Each sequence will have at least one element but no more than 10,000. All elements are between -10,000 and 10,000 (inclusive).
The last line of the input includes a single zero, which is not part of the test cases.

Output

For each test case, write on a separate line, the largest possible sum that can be produced.

Sample

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

Output:
450
2100

hide comments
anurag_tangri: 2018-04-21 10:49:53

Used binary_search() and lower_bound() function . O(n+mlogn)

shivam_2296: 2018-04-07 18:45:34

Hashing + 2 pointers = AC

coding_panda: 2018-04-05 13:57:12

AC in one go ! No dp needed !

yeser: 2018-03-23 03:57:12

tow pointer O(n+m)
or lower_bound O(n+m.logn)
nice problem , tow AC after 6 WA
advice : add big number (eg.10005 ) after last element in arrays

yeser: 2018-03-23 03:57:12

tow pointer O(n+m)
or lower_bound O(n+m.logn)
nice problem , tow AC after 6 WA
advice : add big number (eg.10005 ) after last element in arrays

kaushalag29: 2018-03-04 06:28:15

@pithoriya
Test case should be strictly increasing sequence.

pithoriya: 2018-02-17 10:35:51

SpojToolkit give the wrong answer for the test case
5 5 2 6 8 1
8 5 6 1 2 1 3 4 5
0

sebastiamestre: 2018-01-22 05:40:04

just a sliding window and a (admittedly ad-hoc) greedy in O(N+M) :) easy PZ

ameyanator: 2018-01-19 14:27:19

Not really DP neither Binary Search :P. More like ad-hoc

v_pp_27: 2018-01-15 15:24:21

lower_bound and this test case helped ...
4 -30 -20 -10 10
4 -100 -80 -60 -30
0


Added by:psetter
Date:2009-07-05
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ERL JS-RHINO NODEJS PERL6 VB.NET
Resource:ANARC 2005