熱門文章

2025年12月24日 星期三

ZeroJudge 解題筆記:a159. 11743 - Credit Check

作者:王一哲
日期:2025年12月24日


ZeroJudge 題目連結:a159. 11743 - Credit Check

解題想法


我先將讀取到的測資刪除空格存成字串 code,再將 code 傳入檢查用的自訂函式 check 之中。另外用字典建立偶數位數的對照表,儲存數字乘以 2 再相加的結果。這個對照表建在自訂函式外面程式運作速度比較快。由於測資量很大,Python 要用 sys 加速,否則會超時。

Python 程式碼


使用時間約為 2.6 s,記憶體約為 163.1 MB,通過測試。
import sys

even_map = {'0': 0, '1': 2, '2': 4, '3': 6, '4': 8,
           '5': 1, '6': 3, '7': 5, '8': 7, '9': 9}

def check(s):
    m, tot = len(s), 0
    for c in s[::2]: tot += even_map[c]
    for c in s[1::2]: tot += int(c)
    return tot%10 == 0

n = int(sys.stdin.readline())
lines = sys.stdin.readlines()
result = []
for line in lines:
    code = "".join(line.split())
    if check(code): result.append("Valid\n")
    else: result.append("Invalid\n")
sys.stdout.write("".join(result))

對照表建在自訂函式內,使用時間約為 2.9 s,記憶體約為 163.1 MB,通過測試。
import sys

def check(s):
    even_map = {'0': 0, '1': 2, '2': 4, '3': 6, '4': 8,
                '5': 1, '6': 3, '7': 5, '8': 7, '9': 9}
    m, tot = len(s), 0
    for c in s[::2]: tot += even_map[c]
    for c in s[1::2]: tot += int(c)
    return tot%10 == 0

n = int(sys.stdin.readline())
lines = sys.stdin.readlines()
result = []
for line in lines:
    code = line.strip().replace(" ", "")  # 刪除最後的 \n 及空格
    result.append("Valid\n" if check(code) else "Invalid\n")
sys.stdout.write("".join(result))


C++ 程式碼


使用時間約為 0.5 s,記憶體約為 328 kB,通過測試。
#include <iostream>
#include <string>
#include <map>
using namespace std;

bool check(string s, map<char, int>& even_map) {
    int m = (int)s.size(), tot = 0;
    for(int i=0; i<m; i+=2) tot += even_map[s[i]];
    for(int i=1; i<m; i+=2) tot += s[i] - '0';
    return (tot%10 == 0);
}

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    map<char, int> even_map = 
        {{'0', 0}, {'1', 2}, {'2', 4}, {'3', 6}, {'4', 8},
         {'5', 1}, {'6', 3}, {'7', 5}, {'8', 7}, {'9', 9}};
    int n; cin >> n;
    while(n--) {
        string code = "", tmp;
        for(int i=0; i<4; i++) {
            cin >> tmp;
            code += tmp;
        }      
        cout << (check(code, even_map) ? "Valid\n" : "Invalid\n");
    }
    return 0;
}

對照表建在自訂函式內,使用時間約為 1 s,記憶體約為 344 kB,通過測試。
#include <iostream>
#include <string>
#include <map>
using namespace std;

bool check(string s) {
    map<char, int> even_map = 
        {{'0', 0}, {'1', 2}, {'2', 4}, {'3', 6}, {'4', 8},
         {'5', 1}, {'6', 3}, {'7', 5}, {'8', 7}, {'9', 9}};
    int m = (int)s.size(), tot = 0;
    for(int i=0; i<m; i+=2) tot += even_map[s[i]];
    for(int i=1; i<m; i+=2) tot += s[i] - '0';
    return (tot%10 == 0);
}

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int n; cin >> n;
    while(n--) {
        string code = "", tmp;
        for(int i=0; i<4; i++) {
            cin >> tmp;
            code += tmp;
        }      
        cout << (check(code) ? "Valid\n" : "Invalid\n");
    }
    return 0;
}


沒有留言:

張貼留言