日期:2025年4月28日
ZeroJudge 題目連結:k513. P1.停車場 (Parking)
解題想法
寫比較式的時候,從比較嚴格的條件開始寫,依序檢查是否能停在小停車格,如果不行才再檢查是否能停在中停車格,如果還是不行才再檢查是否能停在大停車格。
Python 程式碼
使用時間約為 22 ms,記憶體約為 3.3 MB,通過測試。
S, M, L = map(int, input().split()) # 小、中、大停車格數量
N = int(input()) # N 輛車
cars = sorted(list(map(int, input().split()))) # 車的大小,由小到大排序
tot = 0 # 可停的車子數量
for car in cars: # 依序讀取車的大小
if 1 <= car <= 199: # 可以停在小停車格
if S > 0: # 如果小停車格有剩
S -= 1; tot += 1
elif M > 0: # 如果沒有小停車格,改停中停車格
M -= 1; tot += 1
elif L > 0: # 如果也沒有中停車格,改停大停車格
L -= 1; tot += 1
elif 200 <= car <= 499: # 可以停在中停車格
if M > 0: # 如果中停車格有剩
M -= 1; tot += 1
elif L > 0: # 如果沒有中停車格,改停大停車格
L -= 1; tot += 1
elif car >= 500 and L > 0: # 可以停在大停車格
L -= 1; tot += 1
else: break # 其它狀況,沒有停車格了,中止迴圈
print(tot)
C++ 程式碼
使用時間約為 2 ms,記憶體約為 108 kB,通過測試。
#include <cstdio>
#include <algorithm>
using namespace std;
int main() {
int S, M, L; scanf("%d %d %d", &S, &M, &L); // 小、中、大停車格數量
int N; scanf("%d", &N); // N 輛車
int cars[N]; // 車的大小,由小到大排序
for(int i=0; i<N; i++) scanf("%d", &cars[i]);
sort(cars, cars+N);
int tot = 0; // 可停的車子數量
for(int i=0; i<N; i++) { // 依序讀取車的大小
if (cars[i] >= 1 && cars[i] <= 199) { // 可以停在小停車格
if (S > 0) { // 如果小停車格有剩
S--; tot++;
} else if (M > 0) { // 如果沒有小停車格,改停中停車格
M--; tot++;
} else if (L > 0) { // 如果也沒有中停車格,改停大停車格
L--; tot++;
}
} else if (cars[i] >= 200 && cars[i] <= 499) { // 可以停在中停車格
if (M > 0) { // 如果中停車格有剩
M--; tot++;
} else if (L > 0) { // 如果沒有中停車格,改停大停車格
L--; tot++;
}
} else if (cars[i] >= 500 && L > 0) { // 可以停在大停車格
L--; tot++;
} else break; // 其它狀況,沒有停車格了,中止迴圈
}
printf("%d\n", tot);
return 0;
}
沒有留言:
張貼留言