#include <bits/stdc++.h> using namespace std; constexpr int MAXN = 500000; typedef long long ll; int n; ll a[MAXN + 1]; int s[MAXN + 1]; int p[MAXN + 1]; void LongestSeq() { int len = 1; s[0] = 0; for (int i = 0; i <= n; i++) { if (a[i] < 0) continue; int l = 0; int r = len; // a[s[l]] <= a[i] < a[s[r]] while (l + 1 < r) { int m = (l + r) / 2; if (a[s[m]] <= a[i]) l = m; else r = m; } p[i] = s[l]; s[r] = i; len = max(len, r + 1); } } int Cost() { int cost = 0; for (int i = n; i > 0; i = p[i]) cost += i - p[i] - 1; return cost; } int main() { scanf("%d", &n); a[0] = 0; for (int i = 1; i <= n; i++) { int ai; scanf("%d", &ai); a[i] = a[i - 1] + ai; } if (a[n] < 0) { printf("-1\n"); return 0; } LongestSeq(); printf("%d\n", Cost()); 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 | #include <bits/stdc++.h> using namespace std; constexpr int MAXN = 500000; typedef long long ll; int n; ll a[MAXN + 1]; int s[MAXN + 1]; int p[MAXN + 1]; void LongestSeq() { int len = 1; s[0] = 0; for (int i = 0; i <= n; i++) { if (a[i] < 0) continue; int l = 0; int r = len; // a[s[l]] <= a[i] < a[s[r]] while (l + 1 < r) { int m = (l + r) / 2; if (a[s[m]] <= a[i]) l = m; else r = m; } p[i] = s[l]; s[r] = i; len = max(len, r + 1); } } int Cost() { int cost = 0; for (int i = n; i > 0; i = p[i]) cost += i - p[i] - 1; return cost; } int main() { scanf("%d", &n); a[0] = 0; for (int i = 1; i <= n; i++) { int ai; scanf("%d", &ai); a[i] = a[i - 1] + ai; } if (a[n] < 0) { printf("-1\n"); return 0; } LongestSeq(); printf("%d\n", Cost()); return 0; } |