hdu 4180 RealPhobia

                               RealPhobia

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


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-x/y| 通分以后就是|(a*y-b*x)/(b*y)| 
// 我们要分子变得越小,即 最小可以为 0 (a,b有公约数的时候)
//当a,b互质时|a*y-b*x| = 1 就是解方程 a*y + b*(-x) = 1 or b*x+a*(-y) = 1 ;
// 即用到拓展的欧几里得算法 求出来时有时要取模,然后取分母大的那个

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std ;

#define maxn 100
#define LL long long 
#define mod 9901

void gcd( LL a , LL b , LL &d , LL &x , LL &y )
{
    if( b == 0 )
    {
        d = a ; x = 1 ; y = 0 ;
        return ;
    }
    gcd( b , a%b , d , y , x ) ;
    y -= x*(a/b) ;
}
int main()
{
    int T ;
    LL a , b , d ;
    LL c1 , c2 , d1 , d2 ;
    cin >> T;
    while(T--)
    {
        scanf("%d/%d" , &a , &b ) ;
        gcd(a,b,d,d1,c1) ;
        if( d != 1 )
        {
            printf("%d/%d\n" , a/d,b/d) ;
            continue ;
        }
        if( a == 1 )
        {
            printf("1/%d\n" , b-1 ) ;
            continue ;
        }
        gcd(b,a,d,c2,d2) ;
        d1 = (d1+b)%b ;
        d2 = (-d2+b)%b ;
        c1 = (-c1+a)%a ;
        c2 = (c2+a)%a ;
        if( d2 > d1 ) printf("%d/%d\n",c2,d2) ;
        else  printf("%d/%d\n",c1,d1) ;
    }
}

 

posted @ 2013-10-05 20:40  _log__  阅读(285)  评论(0编辑  收藏  举报