【Codeforces 808 D. Array Division】+ 二分

一道关于数组划分的问题,Vasya需要将数组分为两部分,使得前缀和等于后缀和。通过移动一个元素来实现。题目提供了几个例子说明何时可行,何时不可行。解决方案中提到可以使用二分查找来枚举每个位置,检查是否有合适的位置插入元素以达到平衡。
摘要由CSDN通过智能技术生成

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;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值