C. Number of Ways

链接:https://codeforces.com/contest/466/problem/C

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 .

Input

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.

Output

Print a single integer — the number of ways to split the array into three parts with the same sum.

Examples

input

Copy

5
1 2 3 0 3

output

Copy

2

input

Copy

4
0 1 -1 0

output

Copy

1

input

Copy

2
4 1

output

Copy

0

代码:

#include<bits/stdc++.h>
using namespace std;
long long n,t,l,r,k,s,d,ans,max1=0,b,c,mod=1e9+7;
long long m[500005],a[500005],dp[500005];
int main()
{
	cin>>n;
	m[0]=0;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
		m[i]=m[i-1]+a[i];
	}
	if(m[n]%3!=0)
	ans=0;
	else
	{
		s=m[n]/3;
	    t=0;
	    for(int i=n;i>=1;i--) 
		{
	        t+=a[i];
	        if(t==s) 
			{
	            dp[i]=1;
	        }
	        dp[i]+=dp[i+1];
	    }
	    ans=0;
	    t=0;
	    for(int i=1;i<=n-2;i++) 
		{
	        t+=a[i];
	        if(t==s) 
			{
	            ans+=dp[i+2];
	        }
	    }
	}

	cout<<ans;
} 

 

全部评论

相关推荐

饿魔:看到在线简历了吧
点赞 评论 收藏
分享
12-15 11:27
门头沟学院 Java
哇哇的菜鸡oc:所有人不要理会,就好了,后面他就知道怎么回事了,只能说有的时候市场都是被宰的人搞坏的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务