置頂

我的 VPython 教學文件 (HackMD 版本)

VPython 教學文件目錄 安裝及測試 基本語法 等速度直線運動 自由落下 終端速度 水平抛射 使用For迴圈計算水平抛射資料 斜向抛射 圓周運動 簡諧運動 單擺 木塊彈簧系統分離 重力及簡諧 行星運動 相疊木塊 雙重簡諧運動 一維彈性碰撞 ...

熱門文章

2025年11月12日 星期三

ZeroJudge 解題筆記:h089. 疊披薩

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


ZeroJudge 題目連結:h089. 疊披薩

解題想法


這題就是河內塔。

Python 程式碼


使用時間約為 0.8 s,記憶體約為 3.1 MB,通過測試。
def hanoi(n, src, aux, dst):
    if n == 1:
        print(f"from {src:s} to {dst:s}")
        return
    hanoi(n-1, src, dst, aux)
    print(f"from {src:s} to {dst:s}")
    hanoi(n-1, aux, src, dst)

hanoi(int(input()), "A", "B", "C")


C++ 程式碼


使用時間約為 64 ms,記憶體約為 52 kB,通過測試。
#include <cstdio>

void hanoi(int n, char src, char aux, char dst) {
    if (n == 1) {
        printf("from %c to %c\n", src, dst);
        return;
    }
    hanoi(n-1, src, dst, aux);
    printf("from %c to %c\n", src, dst);
    hanoi(n-1, aux, src, dst);
}

int main() {
    int n; scanf("%d", &n);
    hanoi(n, 'A', 'B', 'C');
    return 0;
}


沒有留言:

張貼留言