#include <cstdio> #include <algorithm> using namespace std; int n; int a[510]; int buc[510 * 510]; unsigned long long int res; int main() { scanf("%d", &n); for(int i = 0; i < n; i++) { scanf("%d", &a[i]); if(i == 0) buc[0] = a[0]; else buc[i] = buc[i - 1] + a[i]; } int buc_cnt = n; for(int i = 1; i < n; i++) { buc[buc_cnt] = a[i]; buc_cnt++; for(int j = i + 1; j < n; j++) { buc[buc_cnt] = buc[buc_cnt - 1] + a[j]; buc_cnt++; } } sort(buc, buc + buc_cnt); for(int i = 0; i < buc_cnt; i++) { unsigned long long int j = i + 1; unsigned long long int k = buc_cnt - 1; while(j < k) { int suma = buc[i] + buc[j] + buc[k]; if(!suma) { if(buc[j] == buc[k]) { unsigned long long int d = k - j + 1; res += d * (d - 1) / 2; break; } unsigned long long int j_cnt = 1; j++; while(j < k && buc[j] == buc[j + 1]) { j_cnt++; j++; } unsigned long long int k_cnt = 1; k--; while(j < k && buc[k] == buc[k - 1]) { k_cnt++; k--; } res += j_cnt * k_cnt; } else if(suma < 0) j++; else k--; } } printf("%lld\n", res); }
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 | #include <cstdio> #include <algorithm> using namespace std; int n; int a[510]; int buc[510 * 510]; unsigned long long int res; int main() { scanf("%d", &n); for(int i = 0; i < n; i++) { scanf("%d", &a[i]); if(i == 0) buc[0] = a[0]; else buc[i] = buc[i - 1] + a[i]; } int buc_cnt = n; for(int i = 1; i < n; i++) { buc[buc_cnt] = a[i]; buc_cnt++; for(int j = i + 1; j < n; j++) { buc[buc_cnt] = buc[buc_cnt - 1] + a[j]; buc_cnt++; } } sort(buc, buc + buc_cnt); for(int i = 0; i < buc_cnt; i++) { unsigned long long int j = i + 1; unsigned long long int k = buc_cnt - 1; while(j < k) { int suma = buc[i] + buc[j] + buc[k]; if(!suma) { if(buc[j] == buc[k]) { unsigned long long int d = k - j + 1; res += d * (d - 1) / 2; break; } unsigned long long int j_cnt = 1; j++; while(j < k && buc[j] == buc[j + 1]) { j_cnt++; j++; } unsigned long long int k_cnt = 1; k--; while(j < k && buc[k] == buc[k - 1]) { k_cnt++; k--; } res += j_cnt * k_cnt; } else if(suma < 0) j++; else k--; } } printf("%lld\n", res); } |