1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <algorithm>
#include <cstdio>

const int MAX_NUMBERS = 501;

int numbers;
int input[MAX_NUMBERS];
std::pair<int, int> seq[MAX_NUMBERS * MAX_NUMBERS / 2];

int main(void)
{
    scanf("%d", &numbers);
    for(int n = 0; n < numbers; ++n)
    {
        scanf("%d", &input[n]);
        if(n)
            input[n] += input[n - 1];
    }

    int s = 0;
    for(int i = 0; i < numbers; ++i)
        for(int j = i; j < numbers; ++j)
            seq[s++] = {input[j] - (i ? input[i - 1] : 0), 1};

    std::sort(seq, seq + s);
    int size = 0;
    int zero = 0;
    for(int i = 1; i < s; ++i)
    {
        if(seq[size].first == 0)
            zero = size;

        if(seq[size].first == seq[i].first)
            ++seq[size].second;
        else
            seq[++size] = seq[i];
    }

    ++size;
    long long int result = seq[zero].first != 0 ? 0 : (long long int)seq[zero].second * (seq[zero].second - 1) * (seq[zero].second - 2) / 6;

    for(int i = 0; i < size - 2; ++i)
    {
        if(seq[i].first + seq[i + 1].first + seq[i + 2].first > 0)
            break;

        if(seq[i].first + seq[size - 1].first + seq[size - 2].first < 0)
            continue;

        s = i + 1;
        int e = size - 1;
        while(s < e)
        {
            int sum = seq[i].first + seq[s].first + seq[e].first;
            if(sum == 0)
            {
                result += (long long int)seq[i].second * seq[s].second * seq[e].second;
                ++s;
                --e;
            }

            else if(sum > 0)
                --e;
            else
                ++s;
        }
    }

    printf("%lld\n", result);
    return 0;
}