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
72
73
74
75
76
77
78
79
80
81
82
/*
 * Author: toko
 * Time: 2024-03-16 19:08:18
 */

#ifndef DEBUG
#define NDEBUG
#pragma GCC optimize("Ofast,unroll-loops")
#else
#pragma GCC optimize("Og")
#endif

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
	iostream::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);

	int n;
	cin >> n;
	vector<int> v(n);
	for (int& x : v)
		cin >> x;

	vector<int> sum(n * (n + 1) / 2);
	for (int i = 0, k = 0; i < n; i++)
	{
		int s = 0;
		for (int j = i; j < n; j++)
		{
			s += v[j];
			sum[k++] = s;
		}
	}

	sort(sum.begin(), sum.end());

	long long ans = 0;

	for (int i = 0; i < (int) sum.size() - 2; i++)
	{
		int a = sum[i];
		int start = i + 1;
		int end = sum.size() - 1;
		while (start < end)
		{
			int b = sum[start];
			int c = sum[end];
			int s = a + b + c;
			if (s == 0)
			{
				if (b == c)
				{
					ans += (long long) (end - start + 1) * (end - start) / 2;
					break;
				}
				int sstart = start;
				start = upper_bound(sum.begin() + start, sum.begin() + end, b) - sum.begin();
				int send = end;
				end = lower_bound(sum.begin() + start, sum.begin() + end, c) - sum.begin() - 1;
				ans += (long long) (start - sstart) * (send - end);
			}
			else if (s > 0)
			{
				end--;
			}
			else
			{
				start++;
			}
		}
	}

	cout << ans << '\n';

	return 0;
}