You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same.
More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that .
The first line contains integer n (1 ≤ n ≤ 5·105), showing how many numbers are in the array. The second line contains n integers a[1], a[2], ..., a[n] (|a[i]| ≤ 109) — the elements of array a.
Print a single integer — the number of ways to split the array into three parts with the same sum.
5 1 2 3 0 3
2
4 0 1 -1 0
1
2 4 1
0
我自己没想出来,这个是我比较喜欢的一种
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
const int ma=5*1e5+10;
typedef long long ll;
using namespace std;
ll a[ma];
ll s=0,n;
vector<int>vec;
ll solve()
{
if(s%3)
return 0;
s/=3;
ll p=0;
for(int i=0; i<n; i++)
{
p+=a[i];
if(p==s)
vec.push_back(i);
}
p=0;
ll ans=0;
for(int i=n-1;i>=0;i--)
{
p+=a[i];
if(p==s)
ans+=lower_bound(vec.begin(),vec.end(),i-1)-vec.begin();
}
return ans;
}
int main()
{
cin>>n;
for(int i=0; i<n; i++)
{
cin>>a[i];
s+=a[i];
}
cout<<solve()<<endl;
return 0;
}
这个也能过,但是不明白all为0时,那个几种为什么是
(cnt-1)*(cnt-2)/2这个,如果你知道,欢迎评论,感激不尽。
#include<iostream>
#include<cstdio>
#include<algorithm>
#define ll long long
using namespace std;
const int ma=500005;
ll a[ma],sum[ma];
int main()
{
int n;
cin>>n;
sum[0]=0;
for(int i=1;i<=n;i++)
{
cin>>a[i];
sum[i]=sum[i-1]+a[i];
}
if(n==1)
cout<<0<<endl;
else
{
ll all=sum[n];
if(all%3!=0)
cout<<0<<endl;
else if(all)
{
ll s=0;
ll w1=all/3;
ll w2=all/3*2;
int cnt=0;
for(int i=1;i<=n;i++)
{
if(sum[i]==w2)
s+=cnt;
if(sum[i]==w1)
cnt++;
}
cout<<s<<endl;
}
else
{
ll cnt=0;
for(int i=1;i<=n;i++)
{
if(sum[i]==0)
cnt++;
}
cout<<(cnt-1)*(cnt-2)/2<<endl;
}
}
return 0;
}