日期:2026年1月22日
ZeroJudge 題目連結:c004. 10812 - Beat the Spread!
解題想法
這題在算數學。假設兩隊的分數分別為 $x, y$ 而且 $x \geq y$,因為分數為大於等於 0 的整數,因此 $s \geq d$。如果測資 $s < d$,直接印出 impossible。 接下來解聯立 $$ x + y = s ~~~~~ x - y = d $$ 將兩式相加可得 $$ 2x = s + d ~\Rightarrow~ x = \frac{s + d}{2} $$ 如果 $s + d$ 是奇數,直接印出 impossible。再將 $x$ 代入其中一條式子可得 $$ y = s - x $$
Python 程式碼
使用時間約為 9 ms,記憶體約為 2.8 MB,通過測試。
n = int(input())
for _ in range(n):
s, d = map(int, input().split())
if d > s:
print("impossible")
continue
xx = s + d
if xx%2 == 1:
print("impossible")
continue
x = xx//2
y = s - x
print(x, y)
C++ 程式碼
使用時間約為 2 ms,記憶體約為 56 kB,通過測試。
#include <cstdio>
int main() {
int n; scanf("%d", &n);
for(int i=0; i<n; i++) {
int s, d; scanf("%d %d", &s, &d);
if (d > s) {
puts("impossible");
continue;
}
int xx = s + d;
if (xx%2 == 1) {
puts("impossible");
continue;
}
int x = xx/2;
int y = s - x;
printf("%d %d\n", x, y);
}
return 0;
}
沒有留言:
張貼留言