#include <bits/stdc++.h> #define pb push_back using namespace std; typedef vector<int> vi; typedef pair<int, int> pii; long long zera(int i, vi&sum, int m) { int ocz = -sum[i]; long long count = 0; int L = i+1, R = m-1; while(L < R) { if(sum[L] + sum[R] == ocz) { /*int ll = L, rr = R; while(ll <= R && sum[L] == sum[ll]) ll++; ll--; while(rr >= L && sum[R] == sum[rr]) rr--; rr--; if(ll < rr) { count += (long long)(ll-L+1)*(R-rr+1); L = ll+1; R = rr-1; }*/ int rr = R; while(rr > L && sum[rr] == sum[R]) { count++; rr--; } L++; /* else { count += (long long)(R-L+1)*(R-L)/2; break; }*/ } else if(sum[L] + sum[R] < ocz) L++; else R--; } return count; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; vi a; vi s; cin >> n; for(int i = 0; i < n; i++) { int k; cin >> k; a.pb(k); } for(int i = 0; i < n; i++) { int suma = 0; for(int j = i; j < n; j++) { suma += a[j]; s.pb(suma); } } sort(s.begin(), s.end()); int m = n*(n + 1)/2; long long ans = 0; for(int i = 0; i < m; i++) ans += zera(i, s, m); cout << ans << "\n"; //for(auto x : s) cout << x << " "; //cout << "\n"; return 0; }
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 | #include <bits/stdc++.h> #define pb push_back using namespace std; typedef vector<int> vi; typedef pair<int, int> pii; long long zera(int i, vi&sum, int m) { int ocz = -sum[i]; long long count = 0; int L = i+1, R = m-1; while(L < R) { if(sum[L] + sum[R] == ocz) { /*int ll = L, rr = R; while(ll <= R && sum[L] == sum[ll]) ll++; ll--; while(rr >= L && sum[R] == sum[rr]) rr--; rr--; if(ll < rr) { count += (long long)(ll-L+1)*(R-rr+1); L = ll+1; R = rr-1; }*/ int rr = R; while(rr > L && sum[rr] == sum[R]) { count++; rr--; } L++; /* else { count += (long long)(R-L+1)*(R-L)/2; break; }*/ } else if(sum[L] + sum[R] < ocz) L++; else R--; } return count; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; vi a; vi s; cin >> n; for(int i = 0; i < n; i++) { int k; cin >> k; a.pb(k); } for(int i = 0; i < n; i++) { int suma = 0; for(int j = i; j < n; j++) { suma += a[j]; s.pb(suma); } } sort(s.begin(), s.end()); int m = n*(n + 1)/2; long long ans = 0; for(int i = 0; i < m; i++) ans += zera(i, s, m); cout << ans << "\n"; //for(auto x : s) cout << x << " "; //cout << "\n"; return 0; } |