1684: [Usaco2005 Oct]Close Encounter
Description
Lacking even a fifth grade education, the cows are having trouble with a fraction problem from their textbook. Please help them. The problem is simple: Given a properly reduced fraction (i.e., the greatest common divisor of the numerator and denominator is 1, so the fraction cannot be further reduced) find the smallest properly reduced fraction with numerator and denominator in the range 1..32,767 that is closest (but not equal) to the given fraction. 找一个分数它最接近给出一个分数. 你要找的分数的值的范围在1..32767
Input
* Line 1: Two positive space-separated integers N and D (1 <= N < D <= 32,767), respectively the numerator and denominator of the given fraction
Output
* Line 1: Two space-separated integers, respectively the numerator and denominator of the smallest, closest fraction different from the input fraction.
Sample Input
Sample Output
OUTPUT DETAILS:
21845/32767 = .666676839503.... ~ 0.666666.... = 2/3.
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 #include<algorithm> 6 #include<queue> 7 #include<set> 8 #include<map> 9 #include<vector> 10 #define maxn 100010 11 #define maxm 500010 12 #define inf 1000000000 13 #define ll long long 14 using namespace std; 15 double abs1(double a){ 16 if(a>=0)return a; 17 else return -a; 18 } 19 int main(){ 20 int a,b,a1,b1; 21 double sum=100; 22 scanf("%d%d",&a,&b); 23 for(int i=1;i<=32767;i++){ 24 int j=(a*i)/b; 25 if(a*i!=b*j){ 26 double sum2=abs1((double)a/b-(double)j/i); 27 if(sum2<sum){ 28 sum=sum2; 29 a1=j; 30 b1=i; 31 } 32 } 33 if(a*i!=b*(j+1)){ 34 double sum2=abs1((double)a/b-(double)(j+1)/i); 35 if(sum2<sum){ 36 sum=sum2; 37 a1=j+1; 38 b1=i; 39 } 40 } 41 } 42 printf("%d %d",a1,b1); 43 return 0; 44 }