#P6446. Code Indentation Transformation

    ID: 19660 Type: Default 1000ms 256MiB

Code Indentation Transformation

Code Indentation Transformation

Zvonkec has the task of reformatting a source code file every day. The irritating part is that the file uses a very unusual indentation style: the number of tab characters (i.e. the Tab key) at the beginning of each line is arbitrary. To help, his editor supports commands that operate on a contiguous block of lines. In one command you can either add or delete exactly one tab at the beginning of each selected line. (Note: you can never delete more tabs from a line than that line currently has.)

You are given an integer n, the number of lines, followed by two sequences of n nonnegative integers. The first sequence specifies the current number of tabs at the beginning of each line, and the second sequence specifies the required number of tabs. Your task is to compute the minimum number of commands needed to transform the current indentation into the required indentation.

A command is defined as follows:

  • Select any contiguous block of lines.
  • Add or delete (remove) exactly one tab at the beginning of each line in that block.

The minimal number of commands required is given by the formula below. Let \(d_i = target_i - current_i\) for \(1 \le i \le n\). Then the answer is calculated as:

[ \text{ans} = \frac{|d_1| + \sum_{i=2}^{n} |d_i - d_{i-1}| + |d_n|}{2} ]

It can be proven that this formula yields the minimum number of commands needed to reach the desired indentation, while ensuring that no command tries to remove more tabs from a line than are present.

inputFormat

The first line contains an integer n (1 ≤ n ≤ 105), the number of lines in the source code file.

The second line contains n space-separated integers representing the current number of tabs at the beginning of each line.

The third line contains n space-separated integers representing the desired number of tabs at the beginning of each line.

outputFormat

Output a single integer, the minimum number of commands required to reformat the code.

sample

3
2 3 5
3 3 4
2

</p>