#include <bits/stdc++.h> #define boost \ ios_base::sync_with_stdio(0); \ cin.tie(0); \ cout.tie(0) #define debug(x) cerr << #x << " " << x << endl #define ll long long #define int long long #define st first #define nd second using namespace std; int cities[500013]; int n, result = INT_MAX; int calculate_result(int mask) { int sum = cities[1]; int res = 0; for (int i = 1, bit = (1 << (n - 2)); i < n; i++, bit >>= 1) { if (mask & bit) { res++; sum += cities[i + 1]; } else { if (sum < 0) { return INT_MAX; } sum = cities[i + 1]; } } return sum < 0 ? INT_MAX : res; } int32_t main() { boost; cin >> n; for (int i = 1; i <= n; i++) { cin >> cities[i]; } for (int i = 0; i < (1 << (n - 1)); i++) { result = min(result, calculate_result(i)); // result = min(result, calculate_result(i)); } result = result == INT_MAX ? -1 : result; cout << result << endl; }
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 | #include <bits/stdc++.h> #define boost \ ios_base::sync_with_stdio(0); \ cin.tie(0); \ cout.tie(0) #define debug(x) cerr << #x << " " << x << endl #define ll long long #define int long long #define st first #define nd second using namespace std; int cities[500013]; int n, result = INT_MAX; int calculate_result(int mask) { int sum = cities[1]; int res = 0; for (int i = 1, bit = (1 << (n - 2)); i < n; i++, bit >>= 1) { if (mask & bit) { res++; sum += cities[i + 1]; } else { if (sum < 0) { return INT_MAX; } sum = cities[i + 1]; } } return sum < 0 ? INT_MAX : res; } int32_t main() { boost; cin >> n; for (int i = 1; i <= n; i++) { cin >> cities[i]; } for (int i = 0; i < (1 << (n - 1)); i++) { result = min(result, calculate_result(i)); // result = min(result, calculate_result(i)); } result = result == INT_MAX ? -1 : result; cout << result << endl; } |