日期:2025年9月3日
ZeroJudge 題目連結:d575. 末日審判
解題想法
這題看起來很簡單,只要計算兩個點之間的距離是否小於、等於半徑即可,但是用 Python 解題時需要用 sys.stdin.readlines() 及 sys.stdour.write() 加速,否則會超時;用 C++ 解題要使用 long long,否則會溢位。
Python 程式碼
第8筆測資超時。
import sys
for line in sys.stdin:
x0, y0, x1, y1, r = map(int, line.split())
if abs(x0-x1) + abs(y0-y1) <= r: print("die")
else: print("alive")
使用時間約為 2.7 s,記憶體約為 113.6 MB,通過測試。
import sys
lines = sys.stdin.read().splitlines() # 一次讀取所有資料,減少讀取次數
results = [] # 儲存要輸出的結果
for line in lines: # 從 lines 依序讀取資料 line
x0, y0, x1, y1, r = map(int, line.split()) # 用 split 拆開 line,轉成 int,存入變數
if abs(x0-x1) + abs(y0-y1) <= r: results.append("die\n") # 先將要輸出的字串加到 results
else: results.append("alive\n")
sys.stdout.write("".join(results)) # 將 results 合併成一個很長的字串再一次輸出
C++ 程式碼
使用時間約為 0.4 s,記憶體約為 88 kB,通過測試。
#include <cstdio>
#include <cmath>
typedef long long LL;
using namespace std;
int main() {
LL x0, y0, x1, y1, r;
while(scanf("%lld %lld %lld %lld %lld", &x0, &y0, &x1, &y1, &r) != EOF) {
if (abs(x0-x1) + abs(y0-y1) <= r) printf("die\n");
else printf("alive\n");
}
return 0;
}
沒有留言:
張貼留言