[codeForce-1006C]-Three Parts of the Array (简单题)

时间:2021-09-05 06:24:38

You are given an array d1,d2,,dnd1,d2,…,dn consisting of nn integer numbers.

Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array.

Let the sum of elements of the first part be sum1sum1, the sum of elements of the second part be sum2sum2 and the sum of elements of the third part be sum3sum3. Among all possible ways to split the array you have to choose a way such that sum1=sum3sum1=sum3and sum1sum1 is maximum possible.

More formally, if the first part of the array contains aa elements, the second part of the array contains bb elements and the third part contains cc elements, then:

 

sum1=1iadi,sum1=∑1≤i≤adi,
sum2=a+1ia+bdi,sum2=∑a+1≤i≤a+bdi,
sum3=a+b+1ia+b+cdi.sum3=∑a+b+1≤i≤a+b+cdi.

 

The sum of an empty array is 00.

Your task is to find a way to split the array such that sum1=sum3sum1=sum3 and sum1sum1 is maximum possible.

Input

The first line of the input contains one integer nn (1n21051≤n≤2⋅105) — the number of elements in the array dd.

The second line of the input contains nn integers d1,d2,,dnd1,d2,…,dn (1di1091≤di≤109) — the elements of the array dd.

Examples
Input
5
1 3 1 1 4
Output
5
Input
5
1 3 2 1 4
Output
4
Input
3
4 1 2
Output
0
Note
In the first example there is only one possible splitting which maximizes sum1: [1,3,1],[ ],[1,4].

In the second example the only way to have sum1=4 is: [1,3],[2,1],[4].

In the third example there is only one way to split the array: [ ],[4,1,2],[ ].

很简单的一道题,开始的时候想多了,两边同时向里面

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
using namespace std;
const int MAX = 2e5 + 10;
long long n, a[MAX], x;
int main() {

    long long sum1 = 0,sum2 = 0,sum0 = 0;
    memset(a,0,sizeof(a));
    scanf("%d", &n );
    for( int i = 1; i <= n; i++ ) {
        scanf("%d",&a[i]);
    }
    int left = 0, right = n+1;
    while(left<right){
        
        if(sum1>sum2){
            right--;
            sum2 += a[right];
            if(left==right)break;
        }
        if(sum2>sum1){
            left++;
            sum1 += a[left];
            if(left==right)break;
        }
        if(sum1==sum2){
            sum0 = sum1;
            left++;
            right--;
            if(left==right)break;
            sum1+=a[left];
            sum2+=a[right];
        }
        
        
    }
    cout<<sum0<<endl; 
     
    return 0; 
}