4月 04, 2009

【解題】Beat the Spread!

@
ACM Volume CVIII 10812 - Beat the Spread!


The Problem

Superbowl Sunday is nearly here. In order to pass the time waiting for the half-time commercials and wardrobe malfunctions, the local hackers have organized a betting pool on the game. Members place their bets on the sum of the two final scores, or on the absolute difference between the two scores.

Given the winning numbers for each type of bet, can you deduce the final scores?


Input

The first line of input contains n, the number of test cases. n lines follow, each representing a test case. Each test case gives s and d, non-negative integers representing the sum and (absolute) difference between the two final scores.


Output

For each test case, output a line giving the two final scores, largest first. If there are no such scores, output a line containing "impossible". Recall that football scores are always non-negative integers.


Sample Input

2
40 20
20 40


Sample Output

30 10
impossible


解題思考

  假設兩隊分數分別為 a、b(a ≧ b),則兩隊分數總和為 s = a + b、兩隊分數差為 d = a - b。

  以此便可以得出:a = (s + d) / 2、b = (s - d) / 2。

  又因為 s + d = 2a (或是 s - d = 2b),且 s 必大於等於 d。

  所以在 s + d 或 s - d 為奇數,或是 s 小於 d 都輸出 "impossible"。否則則依照上面的公式輸出結果,就達成題目要求了。


參考解答(C++)

#include <iostream>

using namespace std;

int main(void)
{
    int n;

    cin >> n;
    for (int i = 0; i < n; i++)
    {
        long s, d;
        cin >> s >> d;

        // s 必大於等於 d, 且 s, d 的差(和)必為偶數
        if (s < d || ((s - d) % 2))
        {
            cout << "impossible" << endl;
        }
        else
        {
            cout << (s + d) / 2 << " " << (s - d) / 2 << endl;
        }
    }

#ifndef ONLINE_JUDGE
    system("pause");
#endif

    return 0;
}

0 回覆:

張貼留言