Fraction |
Accepted:51 |
|
submit:435 |
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 the change all decimal fractions Between 0 and 1 to fraction. In addtion, he says decimal fractions be too complicate, and set That's much more convient than 0.333 A example to a support he theory. So, Renshengge lists a lot of numbers in textbooks and starts he great work. To him dissapoint, he soon realizes that the denominator of the fraction is very big which kills the simplicity that s Upport of his theory. But Renshengge was famous for his persistence, so he decided to sacrifice some accuracy of fractions. Ok, in him new solution, he confines the denominator in [1,1000] and figure out the least absolute different fractions wit H 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 0.9999999999999 0.3333333333333 0.2222222222222
Sample Output1/1 1/3 2/9 TipYou can use a double to save X; |
Test instructions: Divide a decimal into fractions with a denominator of no more than 1000.
The first thing to note is that if x<0.001, the answer is 0 and 1/1000 the one closest to X;
Pre-process decimals, sort, and then two to find the number closest to X.
#include <cstdio> #include <iostream> #include <algorithm> #include <cstring> #include < Cmath>using namespace std;struct node {double x; int d,f;} S[1000010];int Len;int CMP (node A,node b) {if (a.x==b.x) {return a.f<b.f; } return a.x<b.x;} void Init () {len=0; s[len].x=1.0; s[len].d=1; s[len++].f=1; s[len].x=0.0; s[len].d=1; s[len++].f=0; for (int i=2, i<=1000; i++) {for (int j=1; j<i; J + +) {double k=j*1.0/(i*1.0); S[len].x=k; S[len].d=i; S[len++].f=j; }} sort (s,s+len,cmp);} int gcd (int b,int a) {return b==0?a:gcd (a%b,b);} int main () {init (); int t; scanf ("%d", &t); Double X; while (t--) {scanf ("%lf", &x); int l=0,r=len-1; int l=0,r=len-1; int mid= (L+R) >>1; int id=-1; while (L<r) {mid= (l+r) >>1; if (s[mid].x==x) {id=mid; Break } if (s[mid].x>x) {r=r; R=mid-1; } else {l=l; l=mid+1; }} int f,d; if (id==-1) {//Find closest to double min=1; for (int i=l; i<=r; i++) {double p=fabs (x-s[i].x); if (min>p) {min=p; Id=i; }}} F=s[id].f; D=S[ID].D; int K=GCD (D,F); printf ("%d/%d\n", f/k,d/k); } return 0;}
XTU 1236 fraction (two minutes)