置頂

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

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

熱門文章

2026年9月10日 星期四

ZeroJudge 解題筆記:r582.10491 - Cows and Cars

作者:王一哲
日期:2026年9月10日


ZeroJudge 題目連結:r582.10491 - Cows and Cars

解題想法


題目是多筆測資。每組測資有 $3$ 個數字,分別代表牛的數量、汽車的數量、主持人打開門的數量,假設這 $3$ 個數分別存入變數 $cows$、$cars$、$show$,門的數量 $total = cows + cars$。觀眾先選一扇問,主持人打開 $show$ 扇後面是牛的門,計算觀眾換門且選中汽車的機率,答案輸出到小數點後第 5 位。

這題考數學。換門且選中汽車的狀況有 2 種,第 1 種是先選中後面是牛的門,再換到後面是汽車的門,機率為 $$ P_1 = \frac{cows}{total} \times \frac{cars}{total - show - 1} $$ 上式中第 2 項的分母要減 1,扣掉一開始選的門。第 2 種是先選中後面是汽的門,再換到後面是汽車的門,機率為 $$ P_2 = \frac{cars}{total} \times \frac{cars - 1}{total - show - 1} $$ 上式中第 2 項的分子、分母都要減 1,扣掉一開始選的門。兩種機率相加就是答案。

Python 程式碼


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

    def get_tokens():
        for line in sys.stdin:
            for part in line.split():
                yield(int(part))

    tokens = get_tokens()
    
    while True:
        try:
            cows = next(tokens)
            cars = next(tokens)
            show = next(tokens)
        except StopIteration:
            break
        
        # 先選到牛的機率 * 剩下的門有車的機率 + 先選到車的機率 * 剩下的門有車的機率
        total = cows + cars
        ans = cows / total * cars / (total - show - 1) + cars / total * (cars - 1) / (total - show - 1)
        sys.stdout.write(f"{ans:.5f}\n")

if __name__ == "__main__":
    solve()


C++ 程式碼


使用時間約為 1 ms,記憶體約為 3.6 MB,通過測試。
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int cows, cars, show;
    while(cin >> cows >> cars >> show) {
        int total = cows + cars;
        double ans = (double)cows / total * (double)cars / (total - show - 1)
                     + (double)cars / total * ((double)cars - 1) / (total - show - 1);
        cout << fixed << setprecision(5) << ans << "\n";
    }
    return 0;
}


用 printf 指定輸出格式。使用時間約為 1 ms,記憶體約為 1.5 MB,通過測試。
#include <cstdio>

int main() {
    int cows, cars, show;
    while(scanf("%d %d %d", &cows, &cars, &show) != EOF) {
        int total = cows + cars;
        double ans = (double)cows / total * (double)cars / (total - show - 1)
                     + (double)cars / total * ((double)cars - 1) / (total - show - 1);
        printf("%.5lf\n", ans);
    }
    return 0;
}


C 語言程式碼


使用時間約為 1 ms,記憶體約為 1.6 MB,通過測試。
#include <stdio.h>

int main() {
    int cows, cars, show;
    while(scanf("%d %d %d", &cows, &cars, &show) != EOF) {
        int total = cows + cars;
        double ans = (double)cows / total * (double)cars / (total - show - 1)
                     + (double)cars / total * ((double)cars - 1) / (total - show - 1);
        printf("%.5lf\n", ans);
    }
    return 0;
}


沒有留言:

張貼留言