This page is still under construction.

Parts of this page are still being built. What you see may change.

Division

Interview

Time limit1sMemory limit512 MB

Summary
Count ways to cut a sequence into four nonempty contiguous parts with equal sums, allowing negative values.
Level

Medium6 of 10

Topics
Prefix sum, Hash map, Array, Combinatorics
Solved
No attempts yet

Problem

You are given a sequence of NN integers A1,A2,…,ANA_1, A_2, \dots, A_N. You want to split the sequence into four contiguous parts. Each part must contain at least one number, and the sums of the four parts must all be equal. That is, for some i,j,ki, j, k (1≤i<j<k<N1 \le i < j < k < N), split the sequence into [A1,…,Ai],[Ai+1,…,Aj],[Aj+1,…,Ak],[Ak+1,…,AN][A_1, \dots, A_i], [A_{i+1}, \dots, A_j], [A_{j+1}, \dots, A_k], [A_{k+1}, \dots, A_N].

For example, suppose the given sequence is 4,−1,2,1,−3,1,2,2,1,34, -1, 2, 1, -3, 1, 2, 2, 1, 3. If you split it as below, the sums of the parts differ, so this form is not allowed.

[4,−1,2],[1,−3,1,2],[2,1],[3][4, -1, 2], [1, -3, 1, 2], [2, 1], [3]

If you split it as below, the sums of all parts are equal.

[4,−1],[2,1],[−3,1,2,2,1],[3][4, -1], [2, 1], [-3, 1, 2, 2, 1], [3]

The splits below also give equal sums for all parts.

[4,−1],[2,1,−3,1,2],[2,1],[3][4, -1], [2, 1, -3, 1, 2], [2, 1], [3] or [4,−1,2,1,−3],[1,2],[2,1],[3][4, -1, 2, 1, -3], [1, 2], [2, 1], [3]

Write a program that reads the sequence and counts the number of possible ways to split it as above.

Input

The first line gives the length of the sequence, NN.

The second line gives the NN integers A1,A2,…,ANA_1, A_2, \dots, A_N, separated by single spaces.

Output

Print the number of possible ways on the first line.

The answer can be very large, so in C and C++ you must use a variable of type long long, and in Java a variable of type long.

Constraints

  • 4≤N≤100 0004 \le N \le 100\,000
  • For all 1≤i≤N1 \le i \le N, −1 000≤Ai≤1 000-1\,000 \le A_i \le 1\,000

Examples2

  1. Example 1

    Input
    4
    1 1 1 1
    
    Expected output
    1
    
  2. Example 2

    Input
    10
    4 -1 2 1 -3 1 2 2 1 3
    
    Expected output
    3