#include <iostream> #include <vector> using namespace std; int min_r; struct city{ int value; int distance=0; }; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; min_r = n; vector<struct city>cities; bool ft = false; struct city new_city; for(int i=0; i<n; i++){ int num; cin >> num; if(num != 0){ ft = true; new_city.value = num; cities.push_back(new_city); new_city.distance = 1; }else if(ft && num == 0){ new_city.distance++; } } cities[0].distance = 0; new_city.value = 0; new_city.distance = 0; cities.push_back(new_city); for(long long i=0; i<(1<<(cities.size()-2)); i++){ vector<bool> roads; for(long long j=0; j<cities.size()-2; j++){ if(((i>>j)&1)==1){ roads.push_back(false); }else{ roads.push_back(true); } } long long cur_value = cities[0].value; int cur_r = 0; for(int i=0; i<roads.size(); i++){ if(roads[i] == false){ if(cur_value<0){ break; }else{ cur_value = cities[i+1].value; } }else{ cur_r += cities[i+1].distance; cur_value += cities[i+1].value; } } if(cur_value>=0){ min_r = min(min_r, cur_r); } } if(min_r == n){ cout << -1; }else{ cout << min_r; } }
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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | #include <iostream> #include <vector> using namespace std; int min_r; struct city{ int value; int distance=0; }; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; min_r = n; vector<struct city>cities; bool ft = false; struct city new_city; for(int i=0; i<n; i++){ int num; cin >> num; if(num != 0){ ft = true; new_city.value = num; cities.push_back(new_city); new_city.distance = 1; }else if(ft && num == 0){ new_city.distance++; } } cities[0].distance = 0; new_city.value = 0; new_city.distance = 0; cities.push_back(new_city); for(long long i=0; i<(1<<(cities.size()-2)); i++){ vector<bool> roads; for(long long j=0; j<cities.size()-2; j++){ if(((i>>j)&1)==1){ roads.push_back(false); }else{ roads.push_back(true); } } long long cur_value = cities[0].value; int cur_r = 0; for(int i=0; i<roads.size(); i++){ if(roads[i] == false){ if(cur_value<0){ break; }else{ cur_value = cities[i+1].value; } }else{ cur_r += cities[i+1].distance; cur_value += cities[i+1].value; } } if(cur_value>=0){ min_r = min(min_r, cur_r); } } if(min_r == n){ cout << -1; }else{ cout << min_r; } } |