题目链接如下:
这道题目我想到了打表做,但是没想到用log来简化……写了一个比较复杂的版本,严重超时。后来看了别人的题解才做出来。UVa 11809 Floating-Point Numbers(浮点数)_ShannonNansen的博客-CSDN博客
我的代码如下:
- #include
- #include
- #include
- const double EPS = 0.0001;
-
- std::string str;
- int E, temp;
- double M, t, a;
- double ans1[10][31];
- int ans2[10][31];
-
- int main(){
- for(int i = 0; i <= 9; ++i){
- M = 1 - 1.0 / (1 << (i + 1));
- for(int j = 1; j <= 30; ++j){
- E = (1 << j) - 1;
- t = log10(M) + E * log10(2);
- ans2[i][j] = t;
- ans1[i][j] = pow(10, t - ans2[i][j]);
- }
- }
- while(std::cin >> str && str != "0e0"){
- a = std::stod(str.substr(0, 17));
- temp = std::stoi(str.substr(18));
- for(int i = 0; i <= 9; ++i){
- for(int j = 1; j <= 30; ++j){
- if(ans2[i][j] == temp && fabs(a - ans1[i][j]) < EPS){
- printf("%d %d\n", i, j);
- i = 10;
- break;
- }
- }
- }
- }
- return 0;
- }
我严重超时的版本如下:
- #include
- #include
- #include
-
- std::string str;
- int M, E, t, temp, power, prevpower;
- double a, tempa, b, k, preva;
- double ans1[10][31];
- int ans2[10][31];
-
- int main(){
- a = 0;
- k = 1;
- for(M = 0; M <= 9; ++M){
- k *= 0.5;
- a += k;
- t = 0;
- for(E = 1; E <= 30; ++E){
- temp = t + 1;
- t = 2 * t + 1;
- tempa = E == 1 ? a : preva;
- power = E == 1 ? 0 : prevpower;
- while(temp){
- while(tempa < 10 && temp){
- tempa *= 2;
- temp--;
- }
- if(tempa >= 10){
- tempa /= 10;
- power++;
- }
- }
- preva = tempa;
- prevpower = power;
- ans1[M][E] = tempa;
- ans2[M][E] = power;
- }
- }
- while(std::cin >> str && str != "0e0"){
- a = std::stod(str.substr(0, 17));
- temp = std::stoi(str.substr(18));
- for(M = 0; M <= 9; ++M){
- for(E = 1; E <= 30; ++E){
- if(ans2[M][E] == temp && fabs(a - ans1[M][E]) < 0.0001){
- printf("%d %d\n", M, E);
- M = 10;
- break;
- }
- }
- }
- }
- return 0;
- }