Very Favorite Sequence
Time limit6sMemory limit1024 MB
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 , find indices such that .
No algorithm is known for arbitrary integer sequences that is significantly faster than . Bajtek does not know this, so he decided to solve the problem for his Very Favorite Sequence.
Bajtek's favorite sequence consists of integers . The very favorite sequence is built by taking all 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 whose corresponding elements sum to zero. Write a program that computes this number.
Input
The first line contains an integer (), the length of Bajtek's favorite sequence.
The second line contains integers (), the elements of the favorite sequence.
Output
Print one integer: the number of index triples for which the corresponding elements of the very favorite sequence sum to .
Hint
In the first test the very favorite sequence is . The only triple of distinct elements that sums to zero is , 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.