#include<bits/stdc++.h> using namespace std; int n,w,poc = -1,kon,dp[500005]; long long a[500005],pref[500005]; long long suma(int A,int B) { if(A <= 0) return pref[B]; return pref[B] - pref[A - 1]; } int main() { cin>>n; for(int i = 1;i <= n; i++) { cin>>a[i]; pref[i] = pref[i - 1] + a[i]; dp[i] = 1e9; } if(pref[n] < 0) { cout<<-1; return 0; } for(int i = 1;i <= n; i++) for(int j = i;j > 0; j--) if(suma(j,i) >= 0) dp[i] = min(dp[i],dp[j - 1] + i - j); cout<<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 | #include<bits/stdc++.h> using namespace std; int n,w,poc = -1,kon,dp[500005]; long long a[500005],pref[500005]; long long suma(int A,int B) { if(A <= 0) return pref[B]; return pref[B] - pref[A - 1]; } int main() { cin>>n; for(int i = 1;i <= n; i++) { cin>>a[i]; pref[i] = pref[i - 1] + a[i]; dp[i] = 1e9; } if(pref[n] < 0) { cout<<-1; return 0; } for(int i = 1;i <= n; i++) for(int j = i;j > 0; j--) if(suma(j,i) >= 0) dp[i] = min(dp[i],dp[j - 1] + i - j); cout<<dp[n]; return 0; } |