熱門文章

2026年5月16日 星期六

ZeroJudge 解題筆記:d258. 11313 - Gourmet Games

作者:王一哲
日期:2026年5月16日


ZeroJudge 題目連結:d258. 11313 - Gourmet Games

解題想法


用一個 while 迴圈,當 $n \geq m$ 時繼續執行,每次執行時將集數 $cnt$ 加上 n//m,$n$ 改為 n = n//m + n%m。由於最後只能有一個優勝者,$n$ 最後必須等於 1,如果 $n$ 等於 1 輸出 $cnt$,反之輸出 cannot do this。

Python 程式碼


使用時間約為 29 ms,記憶體約為 8.2 MB,通過測試。
t = int(input())
for _ in range(t):
    n, m = map(int, input().split())
    cnt = 0
    while n >= m:
        cnt += n//m
        n = n//m + n%m
    print(cnt if n == 1 else "cannot do this")

使用時間約為 30 ms,記憶體約為 10.6 MB,通過測試。
def solve():
    import sys

    result = []
    data = sys.stdin.read().split() 
    t = int(data[0])
    ptr = 1
    for _ in range(t):  # 只能跑 t 次,否則會吃 OLE
        n = int(data[ptr])
        m = int(data[ptr+1])
        ptr += 2
        cnt = 0
        while n >= m:
            cnt += n//m
            n = n//m + n%m
        if n == 1: result.append(f"{cnt:d}\n")
        else: result.append("cannot do this\n")
    sys.stdout.write("".join(result))

if __name__ == "__main__":
    solve()


C++ 程式碼


使用時間約為 3 ms,記憶體約為 1.5 MB,通過測試。
#include <cstdio>

int main() {
    int T; scanf("%d", &T);
    for(int t=0; t<T; t++) {
        int n, m; scanf("%d %d", &n, &m);
        int cnt = 0;
        while(n >= m) {
            cnt += n/m;
            n = n/m + n%m;
        }
        if (n == 1) printf("%d\n", cnt);
        else puts("cannot do this");
    }
    return 0;
}


沒有留言:

張貼留言