置頂

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

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

熱門文章

2025年4月21日 星期一

ZeroJudge 解題筆記:k255. 鑿井取水 (Water)

作者:王一哲
日期:2025年4月21日



ZeroJudge 題目連結:k255. 鑿井取水 (Water)

解題想法


解題時要注意,水量為 0 不算枯竭。

Python 程式碼


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

for line in sys.stdin:
    n, w = map(int, line.split())  # n 天,每天産生 w 單位的水
    tot = 0  # 水量
    dry = False  # 是否已經枯竭
    for i in range(1, n+1):  # 檢查第 1 ~ n 天
        used = sum(list(map(int, input().split()))[1:])  # 用水量
        tot = tot + w - used  # 更新水量
        if not dry and tot < 0:
            print(i); dry = True
    if not dry: print(-1)


C++ 程式碼


使用時間約為 11 ms,記憶體約為 96 kB,通過測試。
#include <cstdio>
using namespace std;

int main() {
    int n, w;  // n 天,每天産生 w 單位的水
    while(scanf("%d %d", &n, &w) != EOF) {
        int tot = 0;  // 水量
        bool dry = false;  // 是否已經枯竭
        for(int i=1; i<=n; i++) {  // 檢查第 1 ~ n 天
            int m; scanf("%d", &m);  // m 個用戶
            int used = 0;  // 總用水量 used
            for(int j=0; j<m; j++) {
                int u; scanf("%d", &u);  // 每戶的用水量 u
                used += u;
            }
            tot = tot + w - used;  // 更新水量
            if (!dry && tot < 0) {
                printf("%d\n", i); dry = true;
            }
        }
        if (!dry) printf("-1\n");
    }
    return 0;
}


沒有留言:

張貼留言