熱門文章

2025年6月23日 星期一

ZeroJudge 解題筆記:e925. pD. 學號檢查

作者:王一哲
日期:2025年6月23日


ZeroJudge 題目連結:e925. pD. 學號檢查

解題想法


要檢查 4 個部分:
  1. 大學部學號開頭要是 B
  2. s[1], s[2] 必須是數字
  3. s[3:7] 要在院、系、所的集合之中
  4. s[7], s[8] 必須是數字


Python 程式碼


使用時間約為 37 ms,記憶體約為 3.3 MB,通過測試。
n = int(input())  # n 個院、系、組
dep = set(input() for _ in range(n))  # 院、系、組編號
cnt = 0  # 不合法的學號數量
for _ in range(10):  # 讀取 10 行資料
    s = input()  # 學號
    # 大學部學號開頭要是 B,s[1:3] 必須是數字,s[3:7] 要在 dep 之中,s[7:] 必須是數字
    if s[0] == 'B' and s[1:3].isdigit() and s[3:7] in dep and s[7:].isdigit():
        print("Y")  # 合法,印出 Y
    else:
        print("N")  # 不合法,印出 N
        cnt += 1  # 不合法的數量加 1
if cnt == 0: print("0")  # 全部合法,印出 0
elif cnt == 10: print("1")  # 全部不合法,印出 1
else: print(f"0.{cnt:d}")  # 其它狀況,印出 0.X


C++ 程式碼


使用時間約為 3 ms,記憶體約為 364 kB,通過測試。
#include <iostream>
#include <set>
#include <string>
#include <cctype>
using namespace std;

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int n; cin >> n;  // n 個院、系、組
    set<string> dep;  // 院、系、組編號
    for(int i=0; i<n; i++) {
        string s; cin >> s;
        dep.insert(s);
    }
    int cnt = 0;  // 不合法的學號數量
    for(int i=0; i<10; i++) {  // 讀取 10 行資料
        string s; cin >> s;  // 學號
        // 大學部學號開頭要是 B,s[1:3] 必須是數字,s[3:7] 要在 dep 之中,s[7:] 必須是數字
        if (s[0] != 'B') {  // 大學部學號開頭要是 B
            cout << "N\n";  // 不合法,印出 N
            cnt++;  // 不合法的數量加 1
            continue;
        }
        if (!isdigit(s[1]) || !isdigit(s[2])) {  // s[1], s[2] 必須是數字
            cout << "N\n";  // 不合法,印出 N
            cnt++;  // 不合法的數量加 1
            continue;
        }
        if (dep.count(s.substr(3, 4)) == 0) {  // s[3:7] 要在 dep 之中
            cout << "N\n";  // 不合法,印出 N
            cnt++;  // 不合法的數量加 1
            continue;
        }
        if (!isdigit(s[7]) || !isdigit(s[8])) {  // s[7], s[8] 必須是數字
            cout << "N\n";  // 不合法,印出 N
            cnt++;  // 不合法的數量加 1
            continue;
        }
        cout << "Y\n";  // 合法
    }
    if (cnt == 0) cout << "0\n";  // 全部合法,印出 0
    else if (cnt == 10) cout << "1\n";  // 全部不合法,印出 1
    else cout << "0." << cnt << "\n";  // 其它狀況,印出 0.X
    return 0;
}


沒有留言:

張貼留言