AOJ.849 分数 (暴力)
题意分析
每次枚举分子,然后根据给出的分数值,推算出来分母,然后取分母上下几个数进行进一步计算,看看哪个更接近。
一开始想着直接枚举分子和分母,复杂度爆炸。。。
代码总览
#include <cstdio>
#include <algorithm>
#include <cmath>
#define INF 0x3f3f3f3f
using namespace std;
int gcd(int a,int b){while(b^=a^=b^=a%=b);return a;}
int main()
{
int oup,odown;
scanf("%d%d",&oup,&odown);
double tar = 1.0*oup/odown;
double bestnow = 0.0;
double dis = INF;
int up,down;
for(int i =1 ;i<=32767;++i){
double may = odown * i / oup;
for(int k = 0; k<=1; ++k){
int ret = (int)may + k;
if(i == oup && ret == odown) continue;
if((ret<=32767 && ret>=1))
if(gcd(i,ret) ==1 ){
bestnow = i*1.0/ret;
if(fabs(bestnow - tar)<dis){
dis = fabs(bestnow - tar);up = i;down = ret;
}
}
}
}
printf("%d %d",up,down);
return 0;
}