题目大意:
小数化分数,但是分母限制在[1,1000],很明显的枚举,但是在赛场上的时候傻逼了,无论怎么枚举,怎么二分就是wa,wa到死···········。
(ps:我要给出题人寄刀片~~~~),这个题目需要注意的是有可能输出0/1.
1 #include <cmath> 2 #include <cstdio> 3 #include <cstring> 4 #include <iostream> 5 #include <algorithm> 6 using namespace std; 7 const int maxn = 501000; 8 9 struct node 10 { 11 int x, y; 12 }; 13 node stu[maxn]; 14 bool cmp (node a, node b) 15 { 16 return a.x*1.0/a.y < b.x*1.0/b.y ? true : false; 17 } 18 19 int gcd (int a, int b) 20 { 21 return a%b==0?b:gcd(b, a%b); 22 } 23 24 int Bin_Sreach(double n, int low, int high) 25 { 26 while (low <= high) 27 { 28 int mid = (low + high) / 2; 29 double num = stu[mid].x * 1.0 / stu[mid].y; 30 if (num < n) 31 low = mid; 32 if (num > n) 33 high = mid; 34 if (high - low == 1) 35 break; 36 } 37 double num1 = stu[low].x*1.0 / stu[low].y; 38 double num2 = stu[high].x*1.0 / stu[high].y; 39 if (fabs(n - num1) > fabs(n - num2)) 40 return high; 41 return low; 42 } 43 int main () 44 { 45 int t, k = 1; 46 47 stu[0].y = 1; 48 for (int i=1; i<=1000; i++) 49 for (int j=i; j<=1000; j++) 50 { 51 if (gcd(j, i) == 1) 52 { 53 stu[k].x = i; 54 stu[k++].y = j; 55 } 56 } 57 sort (stu, stu+k, cmp); 58 59 scanf ("%d", &t); 60 while (t --) 61 { 62 double n; 63 scanf ("%lf", &n); 64 int p = Bin_Sreach(n, 0, k-1); 65 printf ("%d/%d ", stu[p].x, stu[p].y); 66 } 67 return 0; 68 }