c004: 10812 - Beat the Spread!

  1. 1. 內容
  2. 2. 範例輸入
  3. 3. 範例輸出
  4. 4. 想法
  5. 5. 程式碼

CPE 一顆星選集 49 道必考題

題目連結:https://zerojudge.tw/ShowProblem?problemid=c004

內容

給定兩數之和 a 、差 b (正數),判斷兩數是否為大於等於 0 的整數。

第一列數字代表有幾組測資。如果條件成立,輸出兩數(大的在前),不成立則輸出「impossible」。

範例輸入

4
40 20
20 40
5 1
100 1

範例輸出

30 10
impossible
3 2
impossible

想法

解二元一次聯立方程式。
X + Y = a
X - Y = b

程式碼

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false), cin.tie(nullptr)
using namespace std;

int main(){
fastio;
int n, s, d, x, y;
cin >> n;
while(n--){
cin >> s >> d;
if((s+d) & 1) cout << "impossible";
else {
x = (s+d) >> 1;
y = s-x;
if(y < 0) cout << "impossible";
else cout << x << " " << y;
}
cout << "\n";
}
return 0;
}