题解:此题并不算难,我们设lsum[i]是从1到i所有数组元素的和(前缀和),rsum[i]是从i到n所有数组元素的和,那么现在就是要找到一组i,j,i<j,j-i>=2,lsum[i]=lsum[j]=sum/3。看到题目数据较大,n方算法不划算,所以用一个c数组记录,c[i]表示i之后有多少个rsum[i]与sum/3相等,这样就把时间复杂度降为O(n)了。
感觉主要是前缀和...
#include <iostream>
#include <cstdio>
using namespace std;
int a[500003],c[500003],n;
long long lsum[500003],rsum[500003],sum,ans;
int main()
{
scanf("%d",&n);
for (int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
lsum[i]=a[i]+lsum[i-1];
}
if (sum%3!=0)
{
cout <<0<<endl;
return 0;
}
for (int i=1;i<=n;i++) rsum[i]=sum-lsum[i]+a[i];
for (int i=n;i>=1;i--) if (rsum[i]==sum/3) c[i]=c[i+1]+1;
else c[i]=c[i+1];
for (int i=1;i<=n-1;i++) if (lsum[i]==sum/3) ans+=c[i+2];
cout <<ans<<endl;
return 0;
}