Algorithm


C. Number of Ways
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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

 

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming

#include <stdio.h>

using namespace std;

int const N = 5 * 1e5 + 1;
int arr[N];

int main() {
  int n;
  scanf("%d", &n);
  
  long long t = 0;
  for(int i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
    t += arr[i];
  }
  
  if(t % 3 != 0)
    puts("0");
  else {
    t /= 3;
    
    long long tmp = 0, res = 0, cnt = 0;
    
    for(int i = 0; i < n - 1; i++) {
      tmp += arr[i];
      if(tmp == t * 2)
        res += cnt;
      if(tmp == t)
        cnt++;
    }
  
    printf("%lld\n", res);
  }
  
  return 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
5
1 2 3 0 3

Output

x
+
cmd
2
Advertisements

Demonstration


Codeforces Solution-Number of Ways-Solution in C, C++, Java, Python

Previous
Codeforces solution 1080-B-B. Margarite and the best present codeforces solution
Next
CodeChef solution DETSCORE - Determine the Score CodeChef solution C,C+