Air Conditioner
National Olympiad — Municipal round (2014 season)
Submission name: conditioning.cpp
Problem summary
Determine the room temperature after one hour. Mode f only cools toward the target, h only heats toward it, a reaches the target either way, and v leaves the temperature unchanged.
Input
Room and target temperatures; then one character f,h,a or v.
Output
The resulting room temperature.
Constraints
−50 ≤ room,target ≤ 50.
Worked example
An independently prepared example for this explanation.
Input
10 20 h
Output
20
Solution analysis
- Start with the current temperature as the result. Ventilation requires no change.
- Cooling gives min(room,target), heating gives max(room,target), and automatic mode gives target directly.
- With room 10 and target 20, h heats to 20. With the same temperatures, f cannot heat and leaves the room at 10.
Why it works
Each mode branch implements exactly its allowed direction of change: minimum for cooling, maximum for heating, target for automatic, and unchanged for ventilation. All four possible modes are covered.
Watch out. Cooling cannot warm a cold room. Heating cannot cool a hot room. Negative temperatures still compare normally.
Commented C++17 solution
An independently written complete program with standard headers.
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int room, target;
char mode;
cin >> room >> target >> mode;
int result = room;
// Minimum cools only; maximum heats only.
if (mode == 'f') {
result = min(room, target);
} else if (mode == 'h') {
result = max(room, target);
} else if (mode == 'a') {
result = target;
}
cout << result << '\n';
}