解題思路
用閉區間[lo,hi]表示仍可能的數字,初始為[1,10]。猜g並回答too high,就把hi縮為min(hi,g−1);too low則把lo提高為max(lo,g+1)。區間只會縮小,完整保存目前所有提示的交集。
遇到right on時,最後猜測必須落在區間中才可能誠實。即使中途區間已空,也要讀到right on才能開始新局;判斷後重新設為[1,10]。回答含空白,C++讀兩個詞合併,Python整行讀取,單獨猜測0結束。
Step-by-step animation
示意:10太高、3太低、4太高、2猜中
步驟 1 / 3
排除10以上
10太高後只可能1到9。
lo=1
hi=9
- 猜測
- 10
- 候選數
- 9
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
int g, lo = 1, hi = 10;
while (cin >> g && g) {
string a, b;
cin >> a >> b;
if (a == "right") {
cout << (lo <= g && g <= hi ? "Stan may be honest" : "Stan is dishonest") << '\n';
lo = 1;
hi = 10;
} else if (b == "high")
hi = min(hi, g - 1);
else
lo = max(lo, g + 1);
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。