熱門文章

2025年2月24日 星期一

ZeroJudge 解題筆記:f045. 3. 身分驗證機制 (Verification)

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



ZeroJudge 題目連結:f045. 3. 身分驗證機制 (Verification)

解題想法


因為輸入的編號可能會以 0 開頭,要用字串儲存資料,不能用整數。

Python 程式碼


使用時間約為 25 ms,記憶體約為 3.3 MB,通過測試。
s = input().strip()  # 代號
a, b = 0, 0  # 最大的兩個數字
for c in s:  # 由 s 依序讀取字元 c
    c = int(c)  # 轉成整數
    if c >= a:  # 如果 c 大於等於 a,c 是最大值,b 改為原來的 a
        b = a; a = c
    elif c > b: b = c # 如果 c 小於 a 且 c 大於 b,b 改為 c
if a*a + b*b == int(s[-3:]): print("Good Morning!")
else: print("SPY!")


C++ 程式碼


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

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    string s; cin >> s;  // 代號
    int a = 0, b = 0;  // 最大的兩個數字
    for(char c : s) {  // 由 s 依序讀取字元 c
        int d = c - '0';  // 轉成整數
        if (d >= a) {  // 如果 d 大於等於 a,d 是最大值,b 改為原來的 a
            b = a; a = d;
        } else if (d > b) b = d;  // 如果 d 小於 a 且 d 大於 b,b 改為 d
    }
    if (a*a + b*b == stoi(s.substr(s.size()-3))) cout << "Good Morning!\n";
    else cout << "SPY!\n";
    return 0;
}


沒有留言:

張貼留言