#include <iostream> #include <vector> #include <algorithm> using namespace std; bool…
- User
#include #include #include using namespace std; bool can_achieve(int max_difference, const vector& recommended_temps, int max_changes) { int steps = recommended_temps.size(); int current_lower = recommended_temps[0] - max_difference; int current_upper = recommended_temps[0] + max_difference; int change_count = 0; for (int step = 1; step < steps; ++step) { int next_lower = max(current_lower, recommended_temps[step] - max_difference); int next_upper = min(current_upper, recommended_temps[step] + max_difference); if (next_lower > next_upper) { // A temperature change is needed ++change_count; current_lower = recommended_temps[step] - max_difference; current_upper = recommended_temps[step] + max_difference; } else { current_lower = next_lower; current_upper = next_upper; } return change_count <= max_changes; } vector minimize_unsavoriness(int test_count, const vector<tuple<int, int, vector>>& test_cases) { vector results; for (const auto& test_case: test_cases) { int num_steps = get<0>(test_case); int max_temp_changes = get<1>(test_case); vector recommended_temps = get<2>(test_case); int low = 0; int high = *max_element(recommended_temps.begin(). recommended_temps.end()) - *min_element(recommended_temps.begin(). recommended_temps.end()); while (low < high) { int mid = (low + high) / 2; if (can_achieve(mid, recommended_temps, max_temp_changes)) { high = mid; } else { low = mid + 1; } } results.push_back(low); } return results; }
int main() { int test_count; cin >> test_count; vector<tuple<int, int, vector>> test_cases; for (int i = 0; i < test_count; ++i) { int num_steps, max_temp_changes; cin >> num_steps >> max_temp_changes; vector recommended_temps(num_steps); for (int j = 0; j < num_steps; ++j) { cin >> recommended_temps[j]; } test_cases.push_back(make_tuple(num_steps, max_temp_changes, recommended_temps)); } vector results = minimize_unsavoriness(test_count, test_cases); for (int result: results) { cout << result << endl; } return 0; }
sebug it
- Assistant