#include <iostream> #include <deque> #include <algorithm> #include <set> #include <vector> using namespace std; int main() { int n; cin >> n; std::deque<long long> diffs; for (int i = 0; i < n; ++i) { long long val; cin >> val; diffs.push_back(val); } long long sum_positive = 0; long long sum_negative = 0; for (int i = 0; i < n; ++i) { if (diffs[i] > 0) sum_positive += diffs[i]; else sum_negative += diffs[i]; } long long balance = sum_positive + sum_negative; if (balance < 0) { cout << -1; return 0; } int road = 0; bool change = true; while (change) { change = false; while (!diffs.empty() && diffs.back() <= 0) { long long el = diffs.back(); diffs.pop_back(); if (el < 0) ++road; if (!diffs.empty()) diffs.back() += el; change = true; } while(diffs.size() > 1 && diffs.back() > 0 && diffs[diffs.size() - 1] >= -diffs[diffs.size() - 2]) { long long el = diffs.back(); diffs.pop_back(); ++road; diffs.back() += el; change = true; } while (!diffs.empty() && diffs.front() <= 0) { long long el = diffs.front(); diffs.pop_front(); if (el < 0) ++road; if (!diffs.empty()) diffs.front() += el; change = true; } while(diffs.size() > 1 && diffs[0] > 0 && diffs[0] >= -diffs[1]) { long long el = diffs.front(); diffs.pop_front(); ++road; diffs.front() += el; change = true; } } if (balance == 0 || diffs.size() == 0 ) { cout << road + diffs.size(); 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 76 77 78 79 | #include <iostream> #include <deque> #include <algorithm> #include <set> #include <vector> using namespace std; int main() { int n; cin >> n; std::deque<long long> diffs; for (int i = 0; i < n; ++i) { long long val; cin >> val; diffs.push_back(val); } long long sum_positive = 0; long long sum_negative = 0; for (int i = 0; i < n; ++i) { if (diffs[i] > 0) sum_positive += diffs[i]; else sum_negative += diffs[i]; } long long balance = sum_positive + sum_negative; if (balance < 0) { cout << -1; return 0; } int road = 0; bool change = true; while (change) { change = false; while (!diffs.empty() && diffs.back() <= 0) { long long el = diffs.back(); diffs.pop_back(); if (el < 0) ++road; if (!diffs.empty()) diffs.back() += el; change = true; } while(diffs.size() > 1 && diffs.back() > 0 && diffs[diffs.size() - 1] >= -diffs[diffs.size() - 2]) { long long el = diffs.back(); diffs.pop_back(); ++road; diffs.back() += el; change = true; } while (!diffs.empty() && diffs.front() <= 0) { long long el = diffs.front(); diffs.pop_front(); if (el < 0) ++road; if (!diffs.empty()) diffs.front() += el; change = true; } while(diffs.size() > 1 && diffs[0] > 0 && diffs[0] >= -diffs[1]) { long long el = diffs.front(); diffs.pop_front(); ++road; diffs.front() += el; change = true; } } if (balance == 0 || diffs.size() == 0 ) { cout << road + diffs.size(); return 0; } } |