time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
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 c
elements, 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.
Input
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
.
Output
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
).
Examples
Input
Copy
5 1 3 1 1 4
Output
Copy
5
Input
Copy
5 1 3 2 1 4
Output
Copy
4
Input
Copy
3 4 1 2
Output
Copy
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],[ ]
这个题目就是将一个数组,分为3部分,第一和第三部分数字的和一样的情况下尽可能的大
如果不存在,就输出0
定义x为第一部分的和,y为第三部分的和
如果x<y就x依次从前往后加
x>y就让y从后往前加
当x==y时,sum记录下结果
由于要让它尽可能的大
所以再让x继续向后加
然后直至前后加的位置重合就停止
输出sum即可
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
ll n,a[200009];
while(scanf("%lld",&n)!=EOF)
{
memset(a,0,sizeof(a));
for(int i=1;i<=n;i++) cin>>a[i];
int j=1,k=n;
ll x=a[j],y=a[k],sum=0;
while(j<k)
{
if(x>y)
y+=a[--k];
else if(x<y)
x+=a[++j];
else
{sum=x;x+=a[++j];}
}
cout<<sum<<endl;
}
return 0;
}
.