#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> a(n); for (int& x : a) { cin >> x; } vector<int> sums; for (int i = 0; i < n; i++) { int s = 0; for (int j = i; j < n; j++) { s += a[j]; sums.push_back(s); } } assert((int) sums.size() == n * (n + 1) / 2); long long answer = 0; int pref = 0; // map<int,int> mapka; const int MAGIC = 2 * 500 * 20'000; vector<int> cnt(2*MAGIC+1); for (int i = -1; i < n; i++) { if (i != -1) { pref += a[i]; } for (int x : sums) { answer += cnt[-(pref+x)+MAGIC]; } for (int x : sums) { cnt[x-pref+MAGIC]++; } } map<int,int> mapka; // mapka.clear(); for (int x : sums) { answer -= mapka[-2*x] * 3; if (x % 2 == 0) answer -= mapka[-x/2] * 3; mapka[x]++; } for (int x : sums) { if (x == 0) { answer--; } } assert(answer % 6 == 0); cout << answer / 6 << endl; }
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 | #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> a(n); for (int& x : a) { cin >> x; } vector<int> sums; for (int i = 0; i < n; i++) { int s = 0; for (int j = i; j < n; j++) { s += a[j]; sums.push_back(s); } } assert((int) sums.size() == n * (n + 1) / 2); long long answer = 0; int pref = 0; // map<int,int> mapka; const int MAGIC = 2 * 500 * 20'000; vector<int> cnt(2*MAGIC+1); for (int i = -1; i < n; i++) { if (i != -1) { pref += a[i]; } for (int x : sums) { answer += cnt[-(pref+x)+MAGIC]; } for (int x : sums) { cnt[x-pref+MAGIC]++; } } map<int,int> mapka; // mapka.clear(); for (int x : sums) { answer -= mapka[-2*x] * 3; if (x % 2 == 0) answer -= mapka[-x/2] * 3; mapka[x]++; } for (int x : sums) { if (x == 0) { answer--; } } assert(answer % 6 == 0); cout << answer / 6 << endl; } |