# APCS實作題2025年10月中級第3題:商品包裝地 > 日期:2025年11月日 > 作者:王一哲 > [ZeroJudge 題目連結](https://zerojudge.tw/ShowProblem?problemid=r490) <br /> ## 解題想法 先寫一個自訂函式 check,用來檢查條碼是否合法。原來題目中的條件為 $$ (S_{odd} + 3 \times S_{even}) \% 10 + C = 0 ~\mathrm{or}~ 10 $$ 實際上可以化簡為 $$ (S_{odd} + 3 \times S_{even} + C) \% 10 = 0 $$ 接下來讀取 N 行條碼,如果條碼合法,取出前三位的産地,用字典計數。最後再找出計數器中的最大值及産地。 <br /><br /> ## Python 程式碼 使用時間約為 29 ms,記憶體約為 3.1 MB,通過測試。 ```python= def check(s): # 檢查條碼是否合法 odd = sum(int(c) for c in s[:-1:2]) # 計算奇數位和 even = sum(int(c) for c in s[1:-1:2]) # 計算偶數位和 C = int(s[-1]) # 檢驗碼 total = (odd + 3*even + C) % 10 # 計算結果 return total == 0 # 回傳是否等於 0 N = int(input()) # 條碼數量 cnt = dict() # 産地: 數量 for _ in range(N): # 讀取 N 行測資 code = input() # 條碼 if check(code): # 如果條碼合法 pos = code[:3] # 産地 if pos not in cnt: # 字典計數 cnt[pos] = 1 else: cnt[pos] += 1 # 找最大數量及産地 ans, imax = "", 0 for k, v in cnt.items(): if v > imax: ans = k imax = v print(f"{ans:s} {imax:d}") ``` <br /> ## C++ 程式碼 使用時間約為 5 ms,記憶體約為 364 kB,通過測試。 ```cpp= #include <iostream> #include <string> #include <map> using namespace std; bool check(string s) { // 檢查條碼是否合法 int odd = 0, even = 0, C = s.back() - '0'; // 奇數位和,偶數位和,檢驗碼 for(int i=0; i<(int)s.size()-1; i+=2) { // 計算奇數位和 odd += s[i] - '0'; } for(int i=1; i<(int)s.size()-1; i+=2) { // 計算偶數位和 even += s[i] - '0'; } int total = (odd + 3*even + C) % 10; // 計算結果 return total == 0; // 回傳是否等於 0 } int main() { ios::sync_with_stdio(0); cin.tie(0); int N; cin >> N; // 條碼數量 map<string, int> cnt; // 産地: 數量 for(int i=0; i<N; i++) { // 讀取 N 行測資 string code; cin >> code; // 條碼 if (check(code)) { // 如果條碼合法 string pos = code.substr(0, 3); // 産地 cnt[pos]++; // 字典計數 } } // 找最大數量及産地 string ans = ""; int imax = 0; for(auto it : cnt) { if (it.second > imax) { ans = it.first; imax = it.second; } } cout << ans << " " << imax << "\n"; return 0; } ``` <br /><br /> --- ###### tags:`APCS`、`C++`、`Python`
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.