2015湖南湘潭第七届大学生程序设计比赛
D题
Fraction |
||
Accepted : 133 | Submit : 892 | |
Time Limit : 1000 MS | Memory Limit : 65536 KB |
FractionProblem Description:Everyone has silly periods, especially for RenShengGe. It‘s a sunny day, no one knows what happened to RenShengGe, RenShengGe says that he wants to change all decimal fractions between 0 and 1 to fraction. In addtion, he says decimal fractions are too complicate, and set that is much more convient than 0.33333... as an example to support his theory. So, RenShengGe lists a lot of numbers in textbooks and starts his great work. To his dissapoint, he soon realizes that the denominator of the fraction may be very big which kills the simplicity that support of his theory. But RenShengGe is famous for his persistence, so he decided to sacrifice some accuracy of fractions. Ok, In his new solution, he confines the denominator in [1,1000] and figure out the least absolute different fractions with the decimal fraction under his restriction. If several fractions satifies the restriction, he chooses the smallest one with simplest formation. InputThe first line contains a number T(no more than 10000) which represents the number of test cases. And there followed T lines, each line contains a finite decimal fraction x that satisfies . OutputFor each test case, transform x in RenShengGe‘s rule. Sample Input3 Sample Output1/1 tipYou can use double to save x; |
赛后题目链接:http://202.197.224.59/OnlineJudge2/index.php/Problem/read/id/1236
题意:输出最接近x的分数。分数的分母范围[1,1000]。
思路:打表求出所有的分数,注意0/1这个情况。二分求出分母。最好最后比较一下,因为输出的是最接近x的分数。
代码:
#include<bits/stdc++.h> using namespace std; #define eps 0.00000001 struct gg { double num; int a,b; } ans[2000000]; int cmp(gg x,gg y) { return x.num<y.num; } int main() { int i,j,t; t=0; ans[t].num=0; ans[t].a=0; ans[t++].b=1; for(i=1; i<=1000; i++) { for(j=1; j<i; j++) { if(__gcd(i,j)>1) continue; double x=j*1.0/i; ans[t].num=x; ans[t].a=j; ans[t++].b=i; } } ans[t].num=1; ans[t].a=1; ans[t++].b=1; sort(ans,ans+t,cmp); int T; double x; scanf("%d",&T); while(T--) { scanf("%lf",&x); int l=0,r=t,mid; while(l<r) { mid=(l+r)/2; if(fabs(x-ans[mid].num)<eps) break; if(x>ans[mid].num) l=mid+1; else r=mid; } int sign1=mid-1,sign2=mid,sign3=mid+1,sign; double flag1=10,flag2=10,flag3=10,flag; if(sign1>=0) flag1=ans[sign1].num; if(sign2>=0) flag2=ans[sign2].num; if(sign3>=0) flag3=ans[sign3].num; if(fabs(flag1-x)<fabs(flag2-x)) sign=sign1; else sign=sign2; flag=ans[sign].num; if(fabs(flag-x)>fabs(flag3-x)) sign=sign3; printf("%d/%d\n",ans[sign].a,ans[sign].b); } return 0; }