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;
} 
发布了137 篇原创文章 · 获赞 15 · 访问量 9911

猜你喜欢

转载自blog.csdn.net/Luoriliming/article/details/104005678