此題為APCS 2018 年 6 月檢測的第一題,題目來源為吳邦一老師所提供的「
APCS 2018 年6 月實作題檢測題目分析與解答」,題目內容如下:
此題在高中生程式解題系統的題號為:
e283: APCS 類似題 - 小崴的特殊編碼
筆者採取比較取巧的方式:「查表法」。於是就用字典來實作,Python程式碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| # 讀取正整數 N
n = int(input())
# 字母編碼的對應表
decodeL = {
'0 1 0 1': 'A',
'0 1 1 1': 'B',
'0 0 1 0': 'C',
'1 1 0 1': 'D',
'1 0 0 0': 'E',
'1 1 0 0': 'F'
}
num = []
# 讀取每一行的字母編碼
for i in range(n):
num.append(input())
# 查表輸出對應的字母
for i in range(n):
print(decodeL[num[i]], end='')
|
註:此Python在高中生解題系統會拿到 83% 的分數,要怎麼修改成 100%呢?
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 | import sys
# 字母編碼的對應表
decodeL = {
'0 1 0 1': 'A',
'0 1 1 1': 'B',
'0 0 1 0': 'C',
'1 1 0 1': 'D',
'1 0 0 0': 'E',
'1 1 0 0': 'F'
}
num = []
for i in sys.stdin:
# 讀取正整數 N
n = int(i)
result = ''
# 讀取每一行的字母編碼
for i in range(n):
k = sys.stdin.readline().strip()
result += decodeL[k]
# 查表輸出對應的字母
print(result) |
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 | #include <iostream>
#include <map>
#include <vector>
#include <string>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
// 建立字母編碼表
std::map<std::string, std::string> lDict;
lDict["0 1 0 1"] = "A";
lDict["0 1 1 1"] = "B";
lDict["0 0 1 0"] = "C";
lDict["1 1 0 1"] = "D";
lDict["1 0 0 0"] = "E";
lDict["1 1 0 0"] = "F";
// 讀取正整數 n
int n;
while(cin >> n)
{
// get the return character
cin.get();
vector<string> lVec;
string encodeStr;
for(int i = 0; i < n; i++) {
getline(std::cin, encodeStr);
lVec.push_back(encodeStr);
}
for(int i = 0; i < n; i++) {
encodeStr = lVec[i];
cout << lDict[encodeStr];
}
cout << "\n";
}
return 0;
} |
Java程式碼如下:
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
| import java.util.*;
class Main {
public static void main(String[] args) {
Dictionary lDict = new Hashtable();
lDict.put("0 1 0 1", "A");
lDict.put("0 1 1 1", "B");
lDict.put("0 0 1 0", "C");
lDict.put("1 1 0 1", "D");
lDict.put("1 0 0 0", "E");
lDict.put("1 1 0 0", "F");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
String str;
Vector<String> strVec = new Vector<String>();
for(int i = 0; i < n; i++) {
str = scanner.nextLine();
strVec.add(str);
}
for(int i = 0; i < n; i++) {
System.out.print(lDict.get(strVec.get(i)));
}
}
}
|
除了吳邦一老師所用的方法與查表法之外,我們還可以有什麼方法呢?
若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。