#include <iostream> #include <vector> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int n; std::cin >> n; long long sum = 0; std::vector<long long> points; points.reserve(n); for (int i = 0; i < n; ++i) { long long e; std::cin >> points[i]; sum += points[i]; } if (sum < 0) { std::cout << -1 << std::endl; return 0; } if (sum == 0) { long long start = 0, partialSum = 0, res = 0; int i = 0; while (i < n) { if (partialSum == 0) { while (i < n and points[i] == 0) ++i; if (i == n) break; start = i; } partialSum += points[i]; if (partialSum == 0) { res += i - start; } ++i; } std::cout << res << std::endl; return 0; } long long forcedSegments = 0, firstNegative = -1, partialSum = 0; for (int i = 0; i < n; ++i) { partialSum += points[i]; if (partialSum >= 0) { if (firstNegative >= 0) { forcedSegments += i - firstNegative; firstNegative = -1; } } else { if (firstNegative == -1) firstNegative = i; } } firstNegative = -1; partialSum = 0; for (int i = n - 1; i > -1; --i) { partialSum += points[i]; if (partialSum >= 0) { if (firstNegative >= 0) { forcedSegments += firstNegative - i; firstNegative = -1; } } else { if (firstNegative == -1) firstNegative = i; } } std::cout << (5 * forcedSegments + n) / 6 << std::endl; 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 | #include <iostream> #include <vector> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int n; std::cin >> n; long long sum = 0; std::vector<long long> points; points.reserve(n); for (int i = 0; i < n; ++i) { long long e; std::cin >> points[i]; sum += points[i]; } if (sum < 0) { std::cout << -1 << std::endl; return 0; } if (sum == 0) { long long start = 0, partialSum = 0, res = 0; int i = 0; while (i < n) { if (partialSum == 0) { while (i < n and points[i] == 0) ++i; if (i == n) break; start = i; } partialSum += points[i]; if (partialSum == 0) { res += i - start; } ++i; } std::cout << res << std::endl; return 0; } long long forcedSegments = 0, firstNegative = -1, partialSum = 0; for (int i = 0; i < n; ++i) { partialSum += points[i]; if (partialSum >= 0) { if (firstNegative >= 0) { forcedSegments += i - firstNegative; firstNegative = -1; } } else { if (firstNegative == -1) firstNegative = i; } } firstNegative = -1; partialSum = 0; for (int i = n - 1; i > -1; --i) { partialSum += points[i]; if (partialSum >= 0) { if (firstNegative >= 0) { forcedSegments += firstNegative - i; firstNegative = -1; } } else { if (firstNegative == -1) firstNegative = i; } } std::cout << (5 * forcedSegments + n) / 6 << std::endl; return 0; } |