【Codeforces 808 D. Array Division】+ 二分

来源:互联网 发布:win7网络驱动下载 编辑:程序博客网 时间:2024/06/05 13:21

D. Array Division
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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?
Input
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.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
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.

并不算难的一道题,却因为一点小马虎,差点怀疑思路有问题 QAQ ,枚举每一个位置,然后二分查找前后是否有可以插入的位置

AC代码:

#include<cstdio>typedef long long LL;const int K = 1e5 + 10;LL a[K],sum[K];bool ok(LL ans,int l,int r){    while(l <= r){        int m = (l + r) / 2;        if(sum[m] == ans)            return true;        else if(sum[m] < ans)            l = m + 1;        else            r = m - 1;    }    return false;}int main(){    int n;    scanf("%d",&n);    for(int i = 1; i <= n; i++)        scanf("%lld",&a[i]),sum[i] = sum[i - 1] + a[i];    if(sum[n] & 1)        puts("NO\n");    else{        LL ans = sum[n] / 2,o = 0;        for(int i = 1; i <= n && !o; i++)            if(ok(ans - a[i],1,i - 1) || ok(ans + a[i],i + 1,n))                o = 1;        if(o)            puts("YES");        else            puts("NO");    }    return 0;}
阅读全文
1 0