#include <iostream> #include <algorithm> #include <cmath> #include <vector> #include <string> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <queue> #include <deque> #include <climits> using namespace std; void input (int &n, vector<long long> &arr) { int x; cin >> n; for (int i = 0; i < n; i++) { cin >> x; arr.push_back(x); } } int solve(int &n, vector<long long> &arr) { vector<int> dp(n + 1, -1); dp[0] = 0; for (int i = 0; i < n; i++) { if (dp[i] < 0) continue; long long sum = 0; for (int j = i; j < n; j++) { sum += arr[j]; if (sum >= 0) dp[j + 1] = max(dp[j + 1], dp[i] + 1); } } if (dp[n] == -1) return -1; else return n - dp[n]; } int main() { ios_base::sync_with_stdio(0); int n; vector<long long> arr; input(n, arr); cout << solve(n, arr) << "\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 | #include <iostream> #include <algorithm> #include <cmath> #include <vector> #include <string> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <queue> #include <deque> #include <climits> using namespace std; void input (int &n, vector<long long> &arr) { int x; cin >> n; for (int i = 0; i < n; i++) { cin >> x; arr.push_back(x); } } int solve(int &n, vector<long long> &arr) { vector<int> dp(n + 1, -1); dp[0] = 0; for (int i = 0; i < n; i++) { if (dp[i] < 0) continue; long long sum = 0; for (int j = i; j < n; j++) { sum += arr[j]; if (sum >= 0) dp[j + 1] = max(dp[j + 1], dp[i] + 1); } } if (dp[n] == -1) return -1; else return n - dp[n]; } int main() { ios_base::sync_with_stdio(0); int n; vector<long long> arr; input(n, arr); cout << solve(n, arr) << "\n"; return 0; } |