Educational Codeforces Round 21 D.Array Division(二分)
D. Array Division
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.
题目链接:http://codeforces.com/contest/808/problem/D
题意:在数组中移动一个数 使得分组可以分割成两个数组 使得两个数组之和相等
分析:
首先分两种情况
1. 往后面移动一个数到前面 (维护前缀和 看看后面有没有符合条件的数)
2. 移掉一个数 (移掉第i个数 看看连续的数能不能符合条件)
用二分做,观摩观摩
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const int N=100010; 5 ll s[N],a[N],sum; 6 int n; 7 bool find(int l,int r,ll x) 8 { 9 while(l<=r) 10 { 11 int mid=(l+r)/2; 12 if(s[mid]==x) 13 return 1; 14 if(s[mid]<x) 15 l=mid+1; 16 else r=mid-1; 17 } 18 return 0; 19 } 20 int main() 21 { 22 scanf("%d",&n); 23 for(int i=1;i<=n;i++) 24 { 25 scanf("%lld",&a[i]); 26 sum+=a[i]; 27 s[i]=s[i-1]+a[i];//求前缀和 28 } 29 if(sum&1) 30 { 31 cout<<"NO"<<endl; 32 return 0; 33 } 34 sum/=2; 35 for(int i=1;i<=n;i++) 36 { 37 if(find(i+1,n,sum+a[i])||find(1,i-1,sum-a[i])) 38 { 39 cout<<"YES"<<endl; 40 return 0; 41 } 42 } 43 cout<<"NO"<<endl; 44 return 0; 45 }
作 者:Angel_Kitty
出 处:https://www.cnblogs.com/ECJTUACM-873284962/
关于作者:阿里云ACE,目前主要研究方向是Web安全漏洞以及反序列化。如有问题或建议,请多多赐教!
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
特此声明:所有评论和私信都会在第一时间回复。也欢迎园子的大大们指正错误,共同进步。或者直接私信我
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是作者坚持原创和持续写作的最大动力!
欢迎大家关注我的微信公众号IT老实人(IThonest),如果您觉得文章对您有很大的帮助,您可以考虑赏博主一杯咖啡以资鼓励,您的肯定将是我最大的动力。thx.
我的公众号是IT老实人(IThonest),一个有故事的公众号,欢迎大家来这里讨论,共同进步,不断学习才能不断进步。扫下面的二维码或者收藏下面的二维码关注吧(长按下面的二维码图片、并选择识别图中的二维码),个人QQ和微信的二维码也已给出,扫描下面👇的二维码一起来讨论吧!!!
欢迎大家关注我的Github,一些文章的备份和平常做的一些项目会存放在这里。