揭秘天气之子试炼:巧用算法计算天气预报成功天数
```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]
- 详解银行账户管理代码:开户、存款与取款功能实现(讯飞星火 | 195点数解答 | 2024-08-08 14:53:52)303
- 超详细!逐行解读银行账户管理代码的含义、作用与用法(讯飞星火 | 152点数解答 | 2024-08-08 14:58:48)320
- C语言:银行账户结构体与操作函数的代码解析及使用示例(讯飞星火 | 298点数解答 | 2024-08-08 15:01:11)296
- 代码揭秘:bankaccount *account 的含义与功能解析( | 124点数解答 | 2024-08-08 15:12:48)340
- C 语言揭秘:`bankaccount *account` 与 `account->balance += amount` 的原理及作用 ( | 161点数解答 | 2024-08-08 15:18:14)310
- 代码解析:指针与结构体在银行账户系统中的作用与好处( | 201点数解答 | 2024-08-08 15:39:09)283
- 深度解析:`bankaccount *account` 与 `bankaccount account` 在代码中的差异( | 174点数解答 | 2024-08-08 15:43:13)303
- 揭秘:为何 bankaccounttest 函数用 bankaccount account 而非 bankaccount *account? (字节豆包 | 218点数解答 | 2024-08-08 15:48:26)421
- 解惑:为何deposit函数printf无&,另一函数却有?代码奥秘大揭秘! (字节豆包 | 132点数解答 | 2024-08-08 15:53:07)276
- 揭秘:为何printf中getbalance函数传参的account前要加&? (字节豆包 | 121点数解答 | 2024-08-08 15:56:21)322
- C 语言揭秘:openaccount、deposit、withdraw 函数中 account 前加 & 的原因 (字节豆包 | 142点数解答 | 2024-08-08 16:03:25)319
- C++ 代码实现自定义运算 x@y = x² + y² - xy 及 x@(x+y) 计算(DeepSeek | 215点数解答 | 2025-12-13 15:08:14)73