Codeforces Round #498 (Div. 3) C. Three Parts of the Array
You are given an array d1,d2,…,dn consisting of n 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 sum1, the sum of elements of the second part be sum2 and the sum of elements of the third part be sum3. Among all possible ways to split the array you have to choose a way such that sum1=sum3 and sum1 is maximum possible.
More formally, if the first part of the array contains a elements, the second part of the array contains b elements and the third part contains celements, then:
sum1=∑1≤i≤adi,sum2=∑a+1≤i≤a+bdi,sum3=∑a+b+1≤i≤a+b+cdi.
The sum of an empty array is 0.
Your task is to find a way to split the array such that sum1=sum3 and sum1 is maximum possible.
The first line of the input contains one integer n (1≤n≤2⋅105) — the number of elements in the array d.
The second line of the input contains n integers d1,d2,…,dn (1≤di≤109) — the elements of the array d.
Print a single integer — the maximum possible value of sum1, considering that the condition sum1=sum3 must be met.
Obviously, at least one valid way to split the array exists (use a=c=0 and b=n).
5
1 3 1 1 4
5
5
1 3 2 1 4
4
3
4 1 2
0
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],[ ].
题意:给你n个数,相对顺序不能变,把他分为3个区域,每个区域和分别为sum1,sum2,sum3,区域可以为空,条件:需要sum1==sum3。问你最大的sum1和sum3是多少?
题解:因为分数字的时候相对位置不能变,所以直接两边往中间靠近就可以了。
1 #include<stdio.h> 2 int main() 3 { 4 int n; 5 long long number[200010]; 6 scanf("%d",&n); 7 for (int i=0;i<n;i++) 8 { 9 scanf("%lld",&number[i]); 10 } 11 long long sum1=0;long long sum3=0;long long max=0; 12 int l=0,r=n-1; 13 while(l<=r) 14 { 15 if(sum1<sum3) 16 { 17 sum1+=number[l]; 18 l++; 19 } 20 if(sum1>sum3) 21 { 22 sum3+=number[r]; 23 r--; 24 } 25 if(sum1==sum3) 26 { 27 if(sum1>max) 28 max=sum1; 29 sum1+=number[l]; 30 l++; 31 } 32 } 33 printf("%lld\n",max); 34 }