#include<iostream> #define N 500001 #define B 1048576 using namespace std; const long long linf = 1e17; long long t[B * 2 + 1]; int n, curr; long long pref; const int base = B; const int inf = N; void tree_insert(long long pref, int res) { int a = res + N + base; if (pref < t[a]) { t[a] = pref; a /= 2; while (a > 0) { t[a] = min(t[a * 2], t[a * 2 + 1]); a /= 2; } } } int tree_find(long long pref) { int a = 1; while (a < base) { a *= 2; if (t[a] > pref) { a++; } } return a - N - base; } int main() { ios_base::sync_with_stdio(0); fill(t, t + base * 2 + 1, linf); cin >> n; tree_insert(0, 0); int prev_res = 0, res = 0; for (int i = 1; i <= n; i++) { cin >> curr; pref += curr; res = inf; if (pref >= 0) { if (curr > 0) { res = prev_res; } res = min(res, tree_find(pref) + i - 1); tree_insert(pref, res - i); } prev_res = res; } if (res == inf) { cout << -1 << endl; } else { cout << res << 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 | #include<iostream> #define N 500001 #define B 1048576 using namespace std; const long long linf = 1e17; long long t[B * 2 + 1]; int n, curr; long long pref; const int base = B; const int inf = N; void tree_insert(long long pref, int res) { int a = res + N + base; if (pref < t[a]) { t[a] = pref; a /= 2; while (a > 0) { t[a] = min(t[a * 2], t[a * 2 + 1]); a /= 2; } } } int tree_find(long long pref) { int a = 1; while (a < base) { a *= 2; if (t[a] > pref) { a++; } } return a - N - base; } int main() { ios_base::sync_with_stdio(0); fill(t, t + base * 2 + 1, linf); cin >> n; tree_insert(0, 0); int prev_res = 0, res = 0; for (int i = 1; i <= n; i++) { cin >> curr; pref += curr; res = inf; if (pref >= 0) { if (curr > 0) { res = prev_res; } res = min(res, tree_find(pref) + i - 1); tree_insert(pref, res - i); } prev_res = res; } if (res == inf) { cout << -1 << endl; } else { cout << res << endl; } return 0; } |