熱門文章

2026年2月26日 星期四

ZeroJudge 解題筆記:c091. 00576 - Hiaku Review

作者:王一哲
日期:2026年2月26日


ZeroJudge 題目連結:c091. 00576 - Hiaku Review

解題想法


Python 可以用 split("/") 以斜線分割句字,而 C++ 則是依序讀取字元,讀到 / 時結算前一個句字。依序計算每個句子中的音節數量,但是連續的母音只能算 1 個音節,記錄前方的字元否為母音,如果這個字元不是母音,則音節數量加 1。

Python 程式碼


使用時間約為 7 ms,記憶體約為 2.8 MB,通過測試。
import sys

for line in sys.stdin:
    if line.rstrip() == "e/o/i": break
    sens = line.rstrip().split("/")
    standard = (0, 5, 7, 5)  # 三個句子的標準音節數量
    haiku = True  # 是否符合規則
    for i, sen in enumerate(sens, start=1):
        cnt = 0  # 音節數量
        state = False  # 前方的字元是否為母音 aeiouy
        for c in sen:  # 依序讀取 sen 的字元 c
            if c in "aeiouy": state = True  # 如果 c 是 aeiouy
            else:  # 如果 c 不是 aeiouy
                if state: cnt += 1  # 如果前方的字元是母音,音節數量加 1
                state = False  # 重設狀態
        if state: cnt += 1  # 如果最後是連續母音,cnt 加 1
        if cnt != standard[i]:  # 如果音節數量不合
            print(i)  # 印出 i
            haiku = False  # 不符合規則
            break  # 中止迴圈
    if haiku: print("Y")  # 如果符合規則,印出 Y


C++ 程式碼


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

int check(string s) {  // 輸入字串,輸出判斷結果,如果符合規則輸出 4,否則輸出錯誤的句子編號
    set<char> vowel = {'a', 'e', 'i', 'o', 'u', 'y'};  // 母音
    int idx = 1, cnt = 0, standard[4] = {0, 5, 7, 5};  // 第幾個句子,音節數量,三個句子的標準音節數量
    bool state = false;  // 是否符合規則,前方的字元是否為母音 aeiouy
    for(char c : s) {  // 依序讀取字元
        if (c == '/') {  // 讀到 '/',結算前一句,重設狀態
            if (state) cnt++;  // 如果最後是連續母音,cnt 加 1
            if (cnt != standard[idx]) return idx;  // 如果音節數量不合,回傳 idx
            cnt = 0;  // 重設音節數量
            state = false;  // 重設母音狀態
            idx++;  // 句子編號加 1
        } else if (vowel.count(c) == 1) {  // 如果 c 是 aeiouy
            state = true;  // 如果 
        } else {  // 如果 c 不是 aeiouy
            if (state) cnt++;  // 如果前方的字元是母音,音節數量加 1
            state = false;  // 重設狀態
        }
    }
    if (state) cnt++;  // 如果能跑到這行,在檢查第三句,如果 state 為 true 則 cnt 加 1
    if (cnt != standard[3]) return 3;  // 如果第三句不合,回傳 3
    return 4;  // 跑到最後一行,符合規則,回傳 4
}

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    string line;
    while(getline(cin, line) && line != "e/o/i") { 
        int ans = check(line);
        if (ans == 4) cout << "Y\n";
        else cout << ans << "\n";
    }
    return 0;
}


沒有留言:

張貼留言