#include <cstdio> #include <cstring> int a[500001], best[500001]; int main() { int n; scanf("%d", &n); long long s = 0; for (int i = 1; i <= n; i++) { scanf("%d", a + i); s += a[i]; } if (s < 0) { const int m1 = -1; printf("%d", m1); return 0; } memset(best, -1, sizeof(best)); best[0] = 0; for (int i = 1; i <= n; i++) { long long sumf = 0, sume = 0; int mbest = 500001; if (a[i] == 0) { best[i] = best[i - 1]; } else { for (int j = i; j >= 1; j--) { if (a[j] > 0) sume += a[j]; if (a[j] < 0) sumf += a[j]; if (sume >= -sumf && best[j - 1] >= 0 && i - j + best[j - 1] < mbest) { mbest = i - j + best[j - 1]; } } if (mbest == 500001) { best[i] = -1; } else { best[i] = mbest; } } //printf("i = %d, best = %d\n", i, best[i]); } printf("%d", best[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 | #include <cstdio> #include <cstring> int a[500001], best[500001]; int main() { int n; scanf("%d", &n); long long s = 0; for (int i = 1; i <= n; i++) { scanf("%d", a + i); s += a[i]; } if (s < 0) { const int m1 = -1; printf("%d", m1); return 0; } memset(best, -1, sizeof(best)); best[0] = 0; for (int i = 1; i <= n; i++) { long long sumf = 0, sume = 0; int mbest = 500001; if (a[i] == 0) { best[i] = best[i - 1]; } else { for (int j = i; j >= 1; j--) { if (a[j] > 0) sume += a[j]; if (a[j] < 0) sumf += a[j]; if (sume >= -sumf && best[j - 1] >= 0 && i - j + best[j - 1] < mbest) { mbest = i - j + best[j - 1]; } } if (mbest == 500001) { best[i] = -1; } else { best[i] = mbest; } } //printf("i = %d, best = %d\n", i, best[i]); } printf("%d", best[n]); return 0; } |