题目链接:http://codeforces.com/gym/100889/problem/B
B. Backward and Forward
time limit per test
2.0 s
memory limit per test
256 MB
input
standard input
output
standard 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'.
Example
input
Copy
2
3
1 0 1
5
10 20 20 10 40
output
Copy
0
3
Note
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].
这道题有两点需要注意:
①定义两个数组下标变量i,j,分别从数组最左边和最右边向中间遍历,若a[i]<a[j],则令i=i+1;a[i]=a[i]+a[i-1],若a[i]>a[j],则令j=j-1,a[j]=a[j]+a[j+1], 并且终止条件是i>j而不是i>=n/2
②由于a[i]值上限是10^9,所以定义数组a[i]为长整型就不会wa;
代码如下:
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> typedef long long ll; #define maxn 100010 using namespace std; int main(){ ll t,n,sum; ll a[maxn]; cin>>t; while(t--){ sum=0; cin>>n; for(ll i=0;i<n;i++){ cin>>a[i]; } for(ll i=0,j=n-1;i<=j;){ if(a[i]==a[j]){ i++; j--; } else if(a[i]<a[j]){ i++; a[i]=a[i]+a[i-1]; sum++; } else if(a[i]>a[j]){ j--; a[j]=a[j]+a[j+1]; sum++; } } printf("%lld ",sum); } return 0; }