codeforces 808D

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
*题意: 给定一个序列, 可以将一个元素的的位置随意移动。 问能否分为两个序列,使得两个序列和相等。
分析: 先维护一个前缀和数组 pre[N]。 对于每个点可以将它移动到第一个序列 , 或则第二个序列两种情况。下面讲个小例子。
a b c d e f g h i j
对于 e 点分析 , 假如它移动到第一序列 , 分割点是 c 那么我们可以得到下面的公式:
 pre[c]+arr[e]=sum
假如移动到第二序列 , 分割点是 f , 那么我们可以得到下面的公式:
 pre[f]arr[e]=sum

所以如果可以找到一点 e , 使得:

pre[k]={sumarr[e],sum+arr[e],if (0 <= k < e)if (e < k <=n)

我的代码:

#include <bits/stdc++.h>
#define sc scanf
#define pr printf
using namespace std;

const int N = 110000;
int64_t pre[N] , arr[N];

bool binary_search_ans(int l , int r , int64_t ans);

int main()
{
    int n,i,j;
    sc("%d",&n);
    long long sum = 0;
    for(i=1; i<=n; i++)
    {
        sc("%I64d",&arr[i]);
        sum += arr[i];
        pre[i] = pre[i-1] + arr[i];
    }
    if(sum %2 != 0)
    {
        pr("NO\n"); return 0;
    }
    sum /= 2;
    for(i=1; i<n; i++)
    {
        if(binary_search_ans(i+1,n,sum+arr[i]))
        {
            pr("YES\n"); return 0;
        }
    }
    for(i=1; i<=n; i++)
    {
        if(binary_search_ans(0,i-1,sum-arr[i]))
        {
            pr("YES\n"); return 0;
        }
    }
    pr("NO\n");

    return 0;
}
bool binary_search_ans(int l , int r , int64_t ans)
{
    int mid;
    while(l <= r)
    {
        mid = (l+r)/2;
        if(pre[mid] == ans) return 1;
        if(pre[mid] < ans)
            l = mid + 1;
        else
            r = mid - 1;
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值