#include <iostream> #include <vector> #include <unordered_map> #define N 500002 using namespace std; vector<int> points; unordered_map<int, int> pointsMap; long long prefixSumPower[N] = {0}; long long minDistance[N] = {0}; int main() { ios::sync_with_stdio(false); int n; cin >> n; for (int i = 0; i < n; i++) { int a; cin >> a; if(a != 0) { pointsMap[points.size()] = i; points.push_back(a); } } if (points.empty()) { cout << 0 << endl; exit(0); } prefixSumPower[0] = 0; for (int i = 0; i < points.size(); i++) { prefixSumPower[i+1] = points[i] + prefixSumPower[i]; } minDistance[0] = 0; minDistance[1] = (points[0] < 0) ? INT64_MAX : 0; for (int i = 2; i <= points.size(); ++i) { long long mDist = INT64_MAX; if (points[i-1] > 0) { mDist = minDistance[i-1]; } for (int j = 1; j < i; ++j) { if (minDistance[j-1] == INT64_MAX) { continue; } long long power = prefixSumPower[i] - prefixSumPower[j-1]; if (power < 0) { continue; } long long dist = pointsMap[i-1] - pointsMap[j-1] + minDistance[j-1]; mDist = min(mDist, dist); } minDistance[i] = mDist; } long long res = minDistance[points.size()]; res = (res == INT64_MAX) ? -1 : res; cout << res << endl; 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 56 57 58 59 60 61 62 63 64 65 66 | #include <iostream> #include <vector> #include <unordered_map> #define N 500002 using namespace std; vector<int> points; unordered_map<int, int> pointsMap; long long prefixSumPower[N] = {0}; long long minDistance[N] = {0}; int main() { ios::sync_with_stdio(false); int n; cin >> n; for (int i = 0; i < n; i++) { int a; cin >> a; if(a != 0) { pointsMap[points.size()] = i; points.push_back(a); } } if (points.empty()) { cout << 0 << endl; exit(0); } prefixSumPower[0] = 0; for (int i = 0; i < points.size(); i++) { prefixSumPower[i+1] = points[i] + prefixSumPower[i]; } minDistance[0] = 0; minDistance[1] = (points[0] < 0) ? INT64_MAX : 0; for (int i = 2; i <= points.size(); ++i) { long long mDist = INT64_MAX; if (points[i-1] > 0) { mDist = minDistance[i-1]; } for (int j = 1; j < i; ++j) { if (minDistance[j-1] == INT64_MAX) { continue; } long long power = prefixSumPower[i] - prefixSumPower[j-1]; if (power < 0) { continue; } long long dist = pointsMap[i-1] - pointsMap[j-1] + minDistance[j-1]; mDist = min(mDist, dist); } minDistance[i] = mDist; } long long res = minDistance[points.size()]; res = (res == INT64_MAX) ? -1 : res; cout << res << endl; return 0; } |