http://poj.org/problem?id=1650
Integer Approximation
Time Limit: 1000MS | | Memory Limit: 65536K |
Total Submissions: 4945 | | Accepted: 1595 |
Description
The FORTH programming language does not support floating-point arithmetic at all. Its author, Chuck Moore, maintains that floating-point calculations are too slow and most of the time can be emulated by integers with proper scaling. For example, to calculate the area of the circle with the radius R he suggests to use formula like R * R * 355 / 113, which is in fact surprisingly accurate. The value of 355 / 113 ≈ 3.141593 is approximating the value of PI with the absolute error of only about 2*10
-7. You are to find the best integer approximation of a given floating-point number A within a given integer limit L. That is, to find such two integers N and D (1 <= N, D <= L) that the value of absolute error |A - N / D| is minimal.
Input
The first line of input contains a floating-point number A (0.1 <= A < 10) with the precision of up to 15 decimal digits. The second line contains the integer limit L. (1 <= L <= 100000).
Output
Output file must contain two integers, N and D, separated by space.
Sample Input
3.14159265358979
10000
Sample Output
355 113
Source
题意:在L(1 <= L <= 100000)的范围内找N和D使得|A-N/D|的误差最小,看L的数据范围1 <= L <= 100000,时间1S可以直接暴力。
#include<iostream>
#include<cmath>
double minx=100000;
using namespace std;
int main()
{
double A;
int N,D,L;
while(scanf("%lf %d",&A,&L)!=EOF)
{
int i=1,j=1;
while(i<=L&&j<=L)//直接在整个L上遍历
{
double t=fabs((double)j/(double)i-A);
if(t<minx)
{
D=i;
N=j;
minx=t;
}
if((double)j/(double)i>=A)i++;//比A大,分母+1
else if((double)j/(double)i<A)j++;//比A小,分子+1
}
printf("%d %d\n",N,D);
}
return 0;
}
网上还有一种很好的算法二分法,感觉这才是王道,很多情况这种算法都是适用的而不要为TLE而担心。。自己载在这上面不是一两次了。。。下面这两种解题的方法还不会代码不大明白以后在仔细研究
http://www.cnblogs.com/rainydays/archive/2011/09/29/2195088.html
http://hi.baidu.com/findthegateopen/blog/item/f95e4fdb469ce3d3b6fd489f.html