A - 季節の名前 / Season Names 解説 by admin 印刷ページ
gpt-6-astra-mediumOverview
In this problem, you are given a month \(M\) and need to determine the corresponding season and output its English name. By treating December (\(12\)) as \(0\), every season can be represented as three consecutive integers.
Analysis
You can solve this problem correctly by simply branching on each month as described in the problem statement. Since there are at most \(12\) months to check, this straightforward approach will not exceed the time limit.
However, only winter spans across the turn of the year, consisting of December (\(12\)), January (\(1\)), and February (\(2\)). Therefore, trying to determine the season with simple inequalities like the other seasons makes it easy to make a mistake in the conditions.
To address this, we can take the remainder of \(M\) divided by \(12\):
\(x = M \bmod 12\)
Given the constraint \(1 \leq M \leq 12\), only December becomes \(0\), while all other months remain unchanged. This allows us to organize the correspondence with the seasons as follows:
| Range of \(x\) | Season |
|---|---|
| \(0 \leq x \leq 2\) | Winter |
| \(3 \leq x \leq 5\) | Spring |
| \(6 \leq x \leq 8\) | Summer |
| \(9 \leq x \leq 11\) | Autumn |
For example, if \(M = 12\), then \(x = 0\), which is correctly identified as Winter.
Algorithm
- Read the month \(M\).
- Compute \(x = M \bmod 12\).
- Check the conditions in the following order and output the corresponding season name:
- If \(x \leq 2\), output
Winter - Else if \(x \leq 5\), output
Spring - Else if \(x \leq 8\), output
Summer - Otherwise, output
Autumn
- If \(x \leq 2\), output
When using else if, we already know that the preceding conditions did not hold. For instance, by the time the check reaches \(x \leq 5\), we already know \(x > 2\), so this branch corresponds precisely to the range for spring. Similarly, all seasons can be correctly determined.
Complexity
- Time complexity: \(O(1)\)
- Space complexity: \(O(1)\)
We only perform a modulo operation and a constant number of comparisons, and the number of variables used is constant.
Implementation Notes
In C++, the modulo operator is
%. In code, this is written asm % 12.Chain the conditions from smaller ranges using
if,else if, andelse. This ensures that exactly \(1\) season is output.Make sure to output the season names exactly as specified, including case sensitivity:
Spring,Summer,Autumn, andWinter.Source Code
// 問題文から独立に実装: 12 月を 0 に読み替えて 3 か月ごとに区切る
#include <iostream>
int main() {
int m; std::cin >> m;
int x = m % 12; // 12 -> 0, so winter is 0..2
if (x <= 2) std::cout << "Winter" << std::endl;
else if (x <= 5) std::cout << "Spring" << std::endl;
else if (x <= 8) std::cout << "Summer" << std::endl;
else std::cout << "Autumn" << std::endl;
}
This editorial was generated by gpt-6-astra-medium.
投稿日時:
最終更新: