#include <cstdio> #include <algorithm> using i64 = long long; const int N = 5e5 + 10, inf = 1e9; i64 s[N], xs[N]; int dp[N], u[N]; int n, m; void add(int x, int v) { for (; x <= m; x += ~x & x + 1) { u[x] = std::min(u[x], v); } } int get(int x, int r = inf) { for (; x >= 0; x -= ~x & x + 1) { r = std::min(r, u[x]); } return r; } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%lld", &s[i]); s[i] += s[i - 1]; } for (int i = 0; i <= n; ++i) xs[i] = s[i]; std::sort(xs, xs + n + 1); m = std::unique(xs, xs + n + 1) - xs; for (int i = 0; i <= m; ++i) u[i] = inf; for (int i = 0; i <= n; ++i) dp[i] = inf; int p = std::lower_bound(xs, xs + m, 0) - xs; dp[0] = 0; add(p, dp[0] - 1); for (int i = 1; i <= n; ++i) { if (s[i] >= s[i - 1] && dp[i - 1] != inf) dp[i] = dp[i - 1]; p = std::lower_bound(xs, xs + m, s[i]) - xs; dp[i] = std::min(dp[i], get(p) + i); add(p, dp[i] - (i + 1)); } if (dp[n] == inf) puts("-1"); else printf("%d\n", dp[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 | #include <cstdio> #include <algorithm> using i64 = long long; const int N = 5e5 + 10, inf = 1e9; i64 s[N], xs[N]; int dp[N], u[N]; int n, m; void add(int x, int v) { for (; x <= m; x += ~x & x + 1) { u[x] = std::min(u[x], v); } } int get(int x, int r = inf) { for (; x >= 0; x -= ~x & x + 1) { r = std::min(r, u[x]); } return r; } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%lld", &s[i]); s[i] += s[i - 1]; } for (int i = 0; i <= n; ++i) xs[i] = s[i]; std::sort(xs, xs + n + 1); m = std::unique(xs, xs + n + 1) - xs; for (int i = 0; i <= m; ++i) u[i] = inf; for (int i = 0; i <= n; ++i) dp[i] = inf; int p = std::lower_bound(xs, xs + m, 0) - xs; dp[0] = 0; add(p, dp[0] - 1); for (int i = 1; i <= n; ++i) { if (s[i] >= s[i - 1] && dp[i - 1] != inf) dp[i] = dp[i - 1]; p = std::lower_bound(xs, xs + m, s[i]) - xs; dp[i] = std::min(dp[i], get(p) + i); add(p, dp[i] - (i + 1)); } if (dp[n] == inf) puts("-1"); else printf("%d\n", dp[n]); return 0; } |