[原創題]你要跟我數一輩子的數嗎 - 提示、題解
GuguGagaOJ #7 你要跟我數一輩子的數嗎
[原創題]你要跟我數一輩子的數嗎 - 提示、題解
題目簡介
設計機器人,判斷使用者有沒有好好數數。一次輸入兩行包含名稱及訊息內容(後序式),遇到每當規則被破壞時立刻輸出一行名稱及目前數到的數,並重置數數進度。最後輸出最高紀錄。
提示
推薦打開之後想想看再繼續,不要一次使用全部
提示1
忘記怎麼處理EOF了?去第一題的題解看看!
提示2
先試試看子題1(訊息都正常數數)?
提示3
後序式求值…怎麼把待處理的數字存起來?
題解
點開會有完整解答,請想過後再開喔
思路
子題一可以透過迴圈及紀錄上一個傳送訊息的人、上一個數到的數字來快速解決。然而在處理後序式求值需要比較有技術了。透過stack,將數字放進去,遇到運算子就拿兩個數字出來算再放回去,如果過程夠拿,且最後恰好剩下一個,則最後留下的值就是解答!
處理後序式時我會建立一個函數,但如果遇到錯誤時需要有一個適當的處理方式。在C++中,我會使用optional(使用方法我有介紹過),而Python, Java等語言可以直接return null。
完整程式碼
請注意,本程式碼僅供寫法上參考,直接複製貼上程式碼會導致你學不到任何東西。
C++ 範例程式碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <bits/stdc++.h>
using namespace std;
#define raymondwengcode ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
optional<int> f(string s) {
stringstream ss(s);
stack<int> st;
string t;
while (ss >> t) {
if (t == "+") {
if (st.size() >= 2) {
int b = st.top(); st.pop();
int a = st.top(); st.pop();
st.push(a + b);
}else {
return nullopt;
}
} else if (t == "-") {
if (st.size() >= 2) {
int b = st.top(); st.pop();
int a = st.top(); st.pop();
st.push(a - b);
}else {
return nullopt;
}
} else if (t == "*") {
if (st.size() >= 2) {
int b = st.top(); st.pop();
int a = st.top(); st.pop();
st.push(a * b);
}else {
return nullopt;
}
} else if (t == "/") {
if (st.size() >= 2) {
int b = st.top(); st.pop();
int a = st.top(); st.pop();
if (b == 0) return nullopt;
st.push(a / b);
}else {
return nullopt;
}
} else {
try {
int num = stoi(t);
st.push(num);
}catch (...) {
return nullopt;
}
}
}
if (st.size() == 1) {
return st.top();
}
return nullopt;
}
int main() {
raymondwengcode;
string name, s;
string last = "";
int cnt = 0;
int m = 0;
while (getline(cin, name)) {
getline(cin, s);
optional<int> res = f(s);
if (name == last || !res || res != cnt+1) {
cout << name << " " << cnt << "\n";
cnt = 0;
last = "";
}else {
cnt++;
m = max(m, cnt);
last = name;
}
}
cout << m;
return 0;
}
Python 範例程式碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def f(s):
stk = []
for i in s:
if i == '+':
if len(stk) < 2:
return None
b = stk.pop()
a = stk.pop()
stk.append(a + b)
elif i == '-':
if len(stk) < 2:
return None
b = stk.pop()
a = stk.pop()
stk.append(a-b)
elif i == '*':
if len(stk) < 2:
return None
b = stk.pop()
a = stk.pop()
stk.append(a * b)
elif i == '/':
if len(stk) < 2:
return None
b = stk.pop()
a = stk.pop()
if b == 0:
return None
stk.append(int(a/b))
else:
stk.append(int(i))
return stk[0] if len(stk) == 1 else None
m = 0
try:
lst = ""
cnt = 0
while True:
name = input()
n = f(input().split())
if n is None or n != cnt+1 or lst == name:
print(f"{name} {cnt}")
lst = ""
cnt = 0
else:
cnt += 1
m = max(m, cnt)
lst = name
except EOFError:
print(m)
本文章以
CC BY 4.0
授權