ACM 算法艺术与信息学竞赛 1.2.4 售货员

来源:互联网 发布:sql倒序查询 编辑:程序博客网 时间:2024/05/02 16:46

题目就不去多说了,就是说有两个浮点数P, Q,给一个整数,使得(P*x, Q*x)之间一定有一个整数,注意了,是不包含P*x, Q*x这两个数的。

看起来也比较简单。

题目链接

售货员

我这个菜鸟居然错了很多次。

下面写一下经历与容易出错的地方。


#include<stdio.h>#include<stdlib.h>double p, q;double from, to, x;int pp, qq;int main(void){while (scanf("%lf%lf", &p, &q) != EOF){p *= 100.0; q *= 100.0; x = 1;    //这里直接用浮点数来进行处理,不要转成int形,比较费时间,后面会说明。while (1){pp = (int)(p * x);qq = (int)(q * x);if(qq/10000-pp/10000>=1 && qq%10000 && pp % 10000) break;  //注意条件x = x + 1;}pp = x;printf("%d\n", pp);}return 0;}

我最主要的原因是超时,我他细查了一下发现:

从浮点数转成整形数,比较耗时间。下面一个VC的代码。


#include<Windows.h>#include<stdio.h>#include<stdlib.h>#include<iostream>using namespace std;double p, q;int a, b;double x[1000];int main(void){int i = 0, j = 0;DWORD start_time, end_time;for (i = 0; i < 1000; ++i)x[i] = (double)rand() / (double)RAND_MAX;start_time = GetTickCount();for (i = 0; i < 1000000000; ++i){for (j = 0; j < 1000; ++j){a = x[j] * 100.0; b = x[j] * 100.0;}}end_time = GetTickCount() - start_time;cout << end_time << endl;start_time = GetTickCount();for (i = 0; i < 1000000000; ++i){for (j = 0; j < 1000; ++j){p = x[j] * 100.0; q = x[j] * 100.0;}}end_time = GetTickCount() - start_time;cout << end_time << endl;return 0;}

84534533996703请按任意键继续. . .

运行结果发现,上面的时间是下面的两倍,就因为中间有个转int的过程。结果导致超时。