您的位置:首页 > 其它

Codeforces 808D

2017-07-11 10:45 369 查看
题目链接

【题意】

给定一个长度为n的序列,问是否可以最多移动一个数字,使该数列可以分成两部分且这两部分和相等,n<=100000


【分析】

可以假设有个隔板从左向右扫(假设这就是最终的划分结果),每次两边的和的差值为x,若能在和较大的序列找到一个数为x/2,则将它放到另一边就满足条件。
这样扫一遍是O(n)的,但是数据是无序的,由于n<=100000,不能通过O(n^2)的暴力查找来做,可以通过平衡树来维护查找是O(logn)的,利用STL就好了
最终复杂度O(nlogn)
注意: x,sum1,sum2都要用long long,即使a[i]<=10^9,x也可能爆int,因为x如果不在a[i]中,是可能超过int范围的.


【Code】

#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<set>
typedef long long LL;
using namespace std;
const double PI = acos(-1.0);
const int MAX_N = 100000 + 10;
multiset<int> s1, s2;
int a[MAX_N];
int main(){
int n;
LL sum1 = 0LL, sum2 = 0LL;
s1.clear();s2.clear();
scanf("%d",&n);
for (int i=0;i<n;i++){
scanf("%d",&a[i]);
sum2 += a[i];
s2.insert(a[i]);
}
if (sum2%2!=0)
{
printf("NO\n");
return 0;
}
multiset<int>::iterator it;
bool ok = false;
for (int i=0;i<n;i++){
sum1 += a[i];
sum2 -= a[i];
s1.insert(a[i]);
it = s2.find(a[i]);
if (it != s2.end()) s2.erase(it);
if (sum1 == sum2) {
ok = true;
break;
}else if (sum1 < sum2){
if ((sum2 - sum1)%2 == 0){
LL x = (sum2 - sum1)/2;
if (x<=1e9)
if (s2.count(x)){
ok = true;
break;
}
}
}else if (sum1 > sum2){
if ((sum1 - sum2)%2 == 0){
LL x = (sum1 - sum2)/2;
if (x<=1e9)
if (s1.count(x)){
ok = true;
break;
}
}
}
}
printf("%s\n",ok ? "YES":"NO");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  codeforces