酷代码 AI
菜单
服务商

揭秘天气之子试炼:巧用算法计算天气预报成功天数

```cpp #include <iostream> #include <vector> #include <unordered_map> using namespace std; // 找到前面所有天中最多的天气(多种天气都是最多时,返回该天气第一次出现最晚的天气种类) int findMostFrequentWeather(const vector<int>& weather, int endDay) { unordered_map<int, int> count; unordered_map<int, int> firstAppearance; // 统计每种天气出现的次数和第一次出现的位置 for (int i = 0; i < endDay; ++i) { if (firstAppearance.find(weather[i]) == firstAppearance.end()) { firstAppearance[weather[i]] = i; } count[weather[i]]++; } int maxCount = 0; int mostFrequent = 0; int latestFirstAppearance = -1; // 找出出现次数最多的天气,若有多个,选择第一次出现最晚的 for (const auto& pair : count) { if (pair.second > maxCount || (pair.second == maxCount && firstAppearance[pair.first] > latestFirstAppearance)) { maxCount = pair.second; mostFrequent = pair.first; latestFirstAppearance = firstAppearance[pair.first]; } } return mostFrequent; } int main() { int n; cin >> n; vector<int> weather(n); // 读取每天的天气情况 for (int i = 0; i < n; ++i) { cin >> weather[i]; } int forecast = weather[0]; int successDays = 0; // 进行预报并统计成功天数 for (int i = 0; i < n; ++i) { if (forecast == weather[i]) { successDays++; } else { if (i > 0) { forecast = findMostFrequentWeather(weather, i + 1); } } if (i < n - 1 && forecast == weather[i]) { continue; } } cout << successDays << endl; return 0; } ``` 代码解释 1. `findMostFrequentWeather` 函数: - 该函数接收一个表示天气情况的向量 `weather` 和表示统计截止天数的 `endDay`。 - 使用两个 `unordered_map` 分别存储每种天气出现的次数 `count` 和第一次出现的位置 `firstAppearance`。 - 遍历截止天数前的所有天气,统计每种天气的相关信息。 - 遍历 `count`,找出出现次数最多的天气,若有多个天气出现次数相同,选择第一次出现最晚的那个。 2. `main` 函数: - 首先读取天数 `n` 和每天的天气情况,存入向量 `weather` 中。 - 初始化预报天气为第一天的天气。 - 遍历每天的天气,若预报正确则成功天数加 1,若预报失败则调用 `findMostFrequentWeather` 函数更新预报天气。 - 最后输出预报成功的天数。 ######[AI问答 | 734点数解答 | 2026-02-07 18:30:34]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]