Under construction

Still being built. Things may change

Very Favorite Sequence

Time limit6sMemory limit1024 MB

Summary
Given an array, count index triples i<j<k in the sequence of all contiguous subarray sums (ordered by start, then end) whose values sum to zero.
Level

Medium7 of 10

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

Problem

3SUM is a well-known algorithmic problem. Given integers c1,c2,…,cmc_1, c_2, \ldots, c_m, find indices i<j<ki < j < k such that ci+cj+ck=0c_i + c_j + c_k = 0.

No algorithm is known for arbitrary integer sequences that is significantly faster than O(m2)O(m^2). Bajtek does not know this, so he decided to solve the problem for his Very Favorite Sequence.

Bajtek's favorite sequence consists of nn integers a1,a2,…,ana_1, a_2, \ldots, a_n. The very favorite sequence is built by taking all n(n+1)/2n(n+1)/2 contiguous subarrays, computing the sum of the elements in each, and placing all these sums into one sequence (repeated values included). The sums are ordered by the starting index of the subarray, and ties are broken by the ending index.

Bajtek is not interested in finding a triple. He wants the exact number of index triples i<j<ki < j < k whose corresponding elements sum to zero. Write a program that computes this number.

Input

The first line contains an integer nn (1≤n≤5001 \le n \le 500), the length of Bajtek's favorite sequence.

The second line contains nn integers aia_i (∣ai∣≤20000|a_i| \le 20000), the elements of the favorite sequence.

Output

Print one integer: the number of index triples i<j<ki < j < k for which the corresponding elements of the very favorite sequence sum to 00.

Hint

In the first test the very favorite sequence is [7,3,1,−4,−6,−2][7, 3, 1, -4, -6, -2]. The only triple of distinct elements that sums to zero is 3+1+(−4)3 + 1 + (-4), so the answer is 1.

In the second test the very favorite sequence consists of 55 zeros. Every triple of indices sums to 0, and there are 26235 such triples.

Examples2

  1. Example 1

    Input
    3
    7 -4 -2
    
    Expected output
    1
    
  2. Example 2

    Input
    10
    0 0 0 0 0 0 0 0 0 0
    
    Expected output
    26235