Break the adjacency

3.5

2 votes
2D dynamic programming, Algorithms, Dynamic Programming
Problem

Alex on his walk to Forest of leaf discovers sticks lying in front of him. Each stick has two values represented by two arrays  and of size where in array ,   denotes length of stick and array ,  denotes price to increment length of stick by unit.

Alex calls an array Broken Adjacency when none of the adjacent sticks has equal length. A stick is adjacent to stick (if any) and stick (if any). He wants to find the minimum cost to achieve Broken Adjacency. To do so, in 1 move he can increment the length of any stick by unit at the price of .

Can you help him find the minimum cost to achieve his goal?

Input Format:

  • The first line contains an integer denoting the number of test cases.
  • The first input line of each test case contains one integer , denoting the number of sticks found.
  • The second line contains space-separated integers denoting the elements of array .
  • The third line contains space-separated integers denoting the elements of array .

Output Format:

Print the minimum cost to make given sticks to Broken Adjacent sticks.

Constraints:

Sample Input
3
3
2 2 3
100 1 10
3
3 3 4
5 1 10
4
1 2 3 4
4 10 1 1
Sample Output
2
2
0
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

For test case 1, 
Alex will increment (i = 1) by 2 units and the final array will look like [ 2, 4, 3 ]. The total cost of this operation will be 2. Alex cannot achieve a lower cost than 2.

For test case 2,
Alex needs to increment the length of stick 3 (i = 1) by 2 units. The final array will look like [ 3, 5, 4 ] , the total cost equals 2.

For test case 3, 
The sticks are already Broken Adjacent.

 

Editor Image

?