RealPhobia


Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 438    Accepted Submission(s): 176



Problem Description


Bert is a programmer with a real fear of floating point arithmetic. Bert has quite successfully used rational numbers to write his programs but he does not like it when the denominator grows large. Your task is to help Bert by writing a program that decreases the denominator of a rational number, whilst introducing the smallest error possible. For a rational number A/B, where B > 2 and 0 < A < B, your program needs to identify a rational number C/D such that:
1. 0 < C < D < B, and
2. the error |A/B - C/D| is the minimum over all possible values of C and D, and
3. D is the smallest such positive integer.


 



Input


The input starts with an integer K (1 <= K <= 1000) that represents the number of cases on a line by itself. Each of the following K lines describes one of the cases and consists of a fraction formatted as two integers, A and B, separated by “/” such that:
1. B is a 32 bit integer strictly greater than 2, and
2. 0 < A < B


 



Output


For each case, the output consists of a fraction on a line by itself. The fraction should be formatted as two integers separated by “/”.


 



Sample Input


3 1/4 2/3 13/21


 



Sample Output


1/3 1/2 8/13


 



Source

大体题意:
给你一个分数A/B,让你找出一个分数C/D满足 两个分数的差的绝对值尽可能小,分母尽可能大。
思路:
A/B-C/D 通分一下得:|(AD-BC)|/BD
先让分子最小,最小肯定是1
所以AD-BC = ±1
令D = x, C = y。
所以满足:Ax - By = 1;或者  -Ax + By = 1;
这样保证了分子最小,会得到两个分数。
在比较两个分数的分母,取一个较大的分母(分数越小)即可!

注意:
输入时分子会等于1,所以这是一个特殊情况, 1/b的形式,那么肯定是 1/b-1 最接近了!
另外  如果输入时分数可以约分的话,先约分,约完分就是答案!
在一点求解欧几里得:
可以先让x,y都为正,在根据公式加符号!
注意还要取模!
详细见代码:

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
void gcd(ll a,ll b,ll &d,ll &x,ll &y){
    if (!b){d = a; x = 1;y = 0;}
    else {gcd(b,a%b,d,y,x); y -= x*(a/b);}
}
int main(){
    int n;
    scanf("%d",&n);
    while(n--){
        ll a,b,x,y,d;
        scanf("%I64d/%I64d",&a,&b);
        gcd(a,b,d,x,y);
        if (d != 1){printf("%I64d/%I64d\n",a/d,b/d);continue;}
        if (a == 1){printf("1/%I64d\n",b-1);continue;}
        ll c1 = (-y+a)%a;
        ll c2 = (y+a)%a;
        ll d1 = (x+b)%b;
        ll d2 = (-x+b)%b;
        if (d1 > d2){printf("%I64d/%I64d\n",c1,d1);}
        else printf("%I64d/%I64d\n",c2,d2);
    }
    return 0;
}