Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
The first line contains single integer n (1 ≤ n ≤ 100000) — the size of the array.
The second line contains n integers a1, a2... an (1 ≤ ai ≤ 109) — the elements of the array.
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
3 1 3 2
YES
5 1 2 3 4 5
NO
5 2 2 3 4 5
YES
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
题意:一个数组,要求移动至多一个数,使数组可以分成前后两个部分,两部分的和相同。
思路:事先计算和s,先从前往后依次相加,每次记录和为t,记录出现的每一个数。当s-t出现过时输出YES,
从后往前也扫一次。 两边只要有一边符合情况即可。
#include<stdio.h>
#include<map>
#define maxn 100010
using namespace std;
long long a[maxn],b[maxn],s;
int n;
int check(long long c[])
{
map<long long ,int> m;
int i,j;
long long t=0;
for(i=0;i<n;i++)
{
t+=c[i];
m[c[i]]=1;
if(m[t-s])
return 1;
}
return 0;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
int i;
s=0;
for(i=0;i<n;i++)
{
scanf("%lld",&a[i]);
b[n-1-i]=a[i];
s+=a[i];
}
if(s%2)
{
printf("NO\n");
continue;
}
s=s/2;
if(check(a)||check(b))
printf("YES\n");
else
printf("NO\n");
}
}