解題思路
把規則保存成(類型,等級,預測),按輸入順序掃描,遇第一個匹配就回傳其編號與Y/N;全不匹配回傳0,N。
固定十天資料依題面保存,逐日套同一函數,將預測與實際比對累計。今天則先將溫度按20、28分界,濕度按30、60分界轉成等級。
因規則有優先序,不能讓後面匹配覆蓋前面結果;三個輸出依序為歷史正確數、今日規則編號、今日預測。
時間O(10N+N),儲存O(N),N≤5。
Step-by-step animation
有序規則的首次匹配|唯一規則T cool Y,其他天預設N。
步驟 1 / 3
規則
唯一規則T cool Y,其他天預設N。
T cool Y
- 預設
- N
#include <bits/stdc++.h>
using namespace std;
struct R {
char t;
string c;
char y;
};
int main() {
int n;
cin >> n;
vector<R> a(n);
for (auto &r : a)
cin >> r.t >> r.c >> r.y;
auto test = [&](string t, string h) {
for (int i = 0; i < n; i++)
if (a[i].c == (a[i].t == 'T' ? t : h))
return pair<int, char>{i + 1, a[i].y};
return pair<int, char>{0, 'N'};
};
vector<array<string, 3>> days = {
{{"mild", "dry", "Y"}}, {{"mild", "normal", "Y"}}, {{"mild", "dry", "Y"}},
{{"hot", "high", "N"}}, {{"hot", "high", "N"}}, {{"hot", "high", "N"}},
{{"hot", "high", "N"}}, {{"hot", "dry", "N"}}, {{"hot", "normal", "N"}},
{{"cool", "dry", "Y"}}};
int score = 0;
for (auto &d : days)
score += test(d[0], d[1]).second == d[2][0];
int x, y;
cin >> x >> y;
auto r = test(x < 20 ? "cool"
: x < 28 ? "mild"
: "hot",
y < 30 ? "dry"
: y < 60 ? "normal"
: "high");
cout << score << "\n" << r.first << "\n" << r.second << "\n";
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。