4月 26, 2009

【解題】Play with Floor and Ceil

@
ACM Volume CVI 10673 - Play with Floor and Ceil


The Problem

For any two integers x and k there exists two more integers p and q such that:



It’s a fairly easy task to prove this theorem, so we’d not ask you to do that. We’d ask for something even easier! Given the values of x and k, you’d only need to find integers p and q that satisfies the given equation.


Input

The first line of the input contains an integer, T (1≤T≤1000) that gives you the number of test cases. In each of the following T lines you’d be given two positive integers x and k. You can safely assume that x and k will always be less than 108.


Output

For each of the test cases print two integers: p and q in one line. These two integers are to be separated by a single space. If there are multiple pairs of p and q that satisfy the equation, any one would do. But to help us keep our task simple, please make sure that the values,



and



fit in a 64 bit signed integer.


Sample Input

3
5 2
40 2
24444 6


Sample Output

1 1
1 1
0 6


解題思考

  由於這一題的解其實不只存在一組,所以每個人的解法可能各有差異。在這裡我只提出我的解法。


  首先,我的想法是,先設 x = c × k + r,其中 0 ≤ r < k。換句話說,就代表 r = x mod k (r 為 x / k 的餘數)。且題目中:



  的值為 c,而:



  在 k 不可整除 x 的情況(即 r 不等於 0)為 c + 1;而在 k 可整除 x 的情況為 c。


  先考慮 k 不可整除 x 的情況:x = c × p + (c + 1) × q = c × (p + q) + q = c × k + r。而在 k 可整除 x 的情況:x = c × p + c × q = c × (p + q) = c × k。

  要讓兩種情況皆成立,則 q = rp = k - q = k - r

  再將此式代入程式,這一題的答案就呼之欲出了。


參考解答(C++)

#include <iostream>

using namespace std;

int main(void)
{
    int n;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        int x, k;
        cin >> x >> k;

        cout << k - (x % k) << " " << (x % k) << endl;
    }

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

    return 0;
}

0 回覆:

張貼留言