「BZOJ1684」[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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #define ll long long using namespace std; inline ll read() { ll x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } int n,m,ans1,ans2; double ans=1e30; inline void cal(int x,int y) { if(x*m==y*n)return; double tmp=abs((double)x/y-(double)n/m); if(tmp<ans) { ans=tmp; ans1=x;ans2=y; } } int main() { n=read();m=read(); for(int j=1;j<=32767;j++) { int i=(double)n/m*j; cal(i,j);cal(i+1,j); } printf("%d %d\n",ans1,ans2); return 0; } |