#include<bits/stdc++.h> using namespace std; long long tab[500009], wyn[500009]; long long infty = 1e9; int main() { long long n,a,b,c; scanf("%lld", &n); for(int i=1; i<=n; i++) scanf("%lld", &tab[i]); for(int i=1; i<=n; i++) wyn[i] = infty; for(int i=1; i<=n; i++) { if(wyn[i-1] < infty) { if(tab[i] == 0) wyn[i] = min(wyn[i], wyn[i-1]); else { a = 0; b = -1; for(int j=i; j<=n; j++) { a += tab[j]; b++; if(a >= 0) wyn[j] = min(wyn[j], wyn[i-1] + b); } } } } if(wyn[n] == infty) printf("-1"); else printf("%lld", wyn[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 | #include<bits/stdc++.h> using namespace std; long long tab[500009], wyn[500009]; long long infty = 1e9; int main() { long long n,a,b,c; scanf("%lld", &n); for(int i=1; i<=n; i++) scanf("%lld", &tab[i]); for(int i=1; i<=n; i++) wyn[i] = infty; for(int i=1; i<=n; i++) { if(wyn[i-1] < infty) { if(tab[i] == 0) wyn[i] = min(wyn[i], wyn[i-1]); else { a = 0; b = -1; for(int j=i; j<=n; j++) { a += tab[j]; b++; if(a >= 0) wyn[j] = min(wyn[j], wyn[i-1] + b); } } } } if(wyn[n] == infty) printf("-1"); else printf("%lld", wyn[n]); return 0; } |