Harry And The Magical Pile

5

1 votes
Sorting, C++, Math, Algorithms, , Basic Math
Problem

Harry is a brilliant student in the class and hence his teacher assigned him a problem. He has been given N piles of stones denoted by an array A where A[i] represents the number of stones in each of the ith piles. All piles are arranged in sequence.

Harry has been asked to make this whole combination magical by performing the below operations some number of times.

  • Choose any two adjacent piles and merge them after merging the new pile formed will have the sum of stones in the two piles before merging.

A combination is magical if the sequence formed by their count of stones is a palindrome. Your task is to help Harry, find the minimum number of operations needed to make the whole combination magical.

Input Format:

  • The first line contains a single integer T denoting the number of test cases.
  • The first line of each test case contains an integer N, denoting the number of elements in the array A
  • The second line of each test case contains N space-separated integers, denoting the elements of array A.

Output Format:

For each test case, print the minimum number of operations needed to make the whole combination magical.

Constraints:

1T10

1N105

0A[i]109

Sample Input
3
4
1 2 3 4
3
1 4 1
7
4 3 2 1 2 3 1
Sample Output
3
0
2
Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

For test case 1:
We need 3 operations here all with the first and second elements. After the first operation, the array will be [3,3,4] after the second it will be [6,4] and after the third, it will be [10] which is the palindrome array. This is the only way to make this combination magical.

For test case 2:
Here the given input array is already magical hence we do not need any extra operations.

For test case 3:
First, we will apply the operation on the 4th and 5th piles the resulting array will be [4,3,2,3,3,1]. Next, we will apply the operation on the 5th and 6th element the resulting array will be[4,3,2,3,4]. Now this array is palindrome and the total operations are 2 which is the minimum possible here.

 

Editor Image

?