#P9422. Array Merge Equivalence

    ID: 22574 Type: Default 1000ms 256MiB

Array Merge Equivalence

Array Merge Equivalence

Given two arrays of positive integers \(\{a_1, a_2, \ldots, a_n\}\) and \(\{b_1, b_2, \ldots, b_m\}\) with equal sums, you can perform merge operations on each array. In one merge operation, you choose an array and merge two adjacent numbers into a single number whose value is the sum of the two. The goal is to perform a sequence of merge operations so that the two arrays become identical; that is, they have the same length \(k\) and for each index \(i\), the \(i\)th element of the first array equals the \(i\)th element of the second array.

It can be shown that if the arrays can be partitioned into segments with equal sums using a greedy two‐pointer method, the minimum number of merge operations required is given by:

[ \text{operations} = (n - k) + (m - k), ]

where \(k\) is the number of matching segments obtained by scanning the arrays. More precisely, using two pointers \(i\) and \(j\) starting at the beginning of each array with \(sumA = a_1\) and \(sumB = b_1\):

  • If \(sumA = sumB\), a matching segment is found and both pointers advance.
  • If \(sumA < sumB\), advance pointer \(i\) and update \(sumA\).
  • If \(sumA > sumB\), advance pointer \(j\) and update \(sumB\).

Return the total minimum merge operations required.

inputFormat

The first line contains two integers \(n\) and \(m\) representing the lengths of the two arrays.

The second line contains \(n\) positive integers \(a_1, a_2, \ldots, a_n\) (separated by spaces).

The third line contains \(m\) positive integers \(b_1, b_2, \ldots, b_m\) (separated by spaces).

It is guaranteed that \(\sum_{i=1}^{n}a_i = \sum_{j=1}^{m}b_j\).

outputFormat

Output one integer, the minimum number of merge operations needed to make the two arrays identical.

sample

3 3
1 2 3
1 2 3
0