Codeforces Gym 100889 B Backward and Forward

B. Backward and Forward

time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output

An array is called a ‘Mirror’ if it reads the same backward and forward. For example, [23, 15, 23] is a ‘Mirror’ but [2, 0, 1] is not.

You are given an array A of size N. Your task is to make a given array a ‘Mirror’. The only allowed operation is that you can merge two adjacent elements in the array and replace them with their sum.

Find minimum number of operations required to make given array a ‘Mirror’ such that it reads the same backward and forward.

Input

First line contains T(1 ≤ T ≤ 20), the number of test cases. Each test case consist of 2 lines. First line contains number N(1 ≤ N ≤ 105), size of the array. Next line contains N space separated integers Ai(0 ≤ Ai ≤ 109) denoting elements in the array A.

Output

For each test case output in one line minimum steps required to make given array a ‘Mirror’.

input

2
3
1 0 1
5
10 20 20 10 40

output

0
3

Sample test case 1:

Given array is already a ‘Mirror’ . So, no need to perform any operation.

Sample test case 2:

One possible sequence of operations.

Step 1 : Merge 2nd and 3rd element to get array [10, 40, 10, 40].

Step 2 : Merge 1st and 2nd element to get array [50, 10, 40].

Step 3 : Merge 2nd and 3rd element to get array [50, 50].


#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

__int64 a[100005];

int main()
{
    int t;
    long long n, i, j;
    scanf("%d", &t);
    while(t--){
        long long op = 0;

        scanf("%lld", &n);

        for(i = 0; i < n; i++){
            scanf("%I64d", &a[i]);
        }

        for(i = 0, j = n-1; i <= j; ){
            if(a[i]==a[j]){
                i++;
                j--;
            }
            else if(a[i] > a[j]){ // 需要从尾部开始合并 
                j--;
                a[j]+=a[j+1];
                op++;
            }
            else{   //从头部开始合并 
                i++;
                a[i]+=a[i-1];
                op++;
            }
        }
        printf("%lld\n", op);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值