目录
Hangover
要求:
总时间限制: 1000ms
内存限制: 65536kB
描述:
How far can you make a stack of cards overhang a table? If you have one card, you can create a maximum overhang of half a card length. (We're assuming that the cards must be perpendicular(垂直的) to the table.) With two cards you can make the top card overhang the bottom one by half a card length, and the bottom one overhang the table by a third of a card length, for a total maximum overhang of 1/2 + 1/3 = 5/6 card lengths. In general you can make n cards overhang by 1/2 +1/3 + 1/4 + ... + 1/(n + 1) card lengths, where the top card overhangs the second by 1/2, the second overhangs tha third by 1/3, the third overhangs the fourth by 1/4, etc., and the bottom card overhangs the table by 1/(n + 1). This is illustrated in the figure below.
输入:
The input consists of one or more test cases, followed by a line containing the number 0.00 that signals the end of the input. Each test case is a single line containing a positive floating-point number c whose value is at least 0.01 and at most 5.20; c will contain exactly three digits.
输出:
For each test case, output the minimum number of cards necessary to achieve an overhang of at least c card lengths. Use the exact output format shown in the examples.
样例输入:
1.00 3.71 0.04 5.19 0.00
样例输出:
3 card(s) 61 card(s) 1 card(s) 273 card(s)
问题分析:
通过分析英文题干,我们得知目标是对于一个给定的两位小数c,我们需要计算该式
什么时候刚好大于c,也就能令题干中的卡片等够平稳放置在桌面之上。
题目的输入以输入0.00作为结束,也代表着我们不知道测试数据中究竟会有多少个数据,但我们可以发现c是有大小限制的: .而当c=5.19时,根据样例我们知道n=273,所以我们估计n的最大值应该不会超过300.
(实际上c=5.20时n=276)
一种很直接的思路是,对于每一个给定的c值,我们都从 开始枚举,直到找到所求的n. 这样做显然会有大量的重复计算。所以我们不妨使用记忆化存储,提前算好n在不同值下,对应的浮点数,最后用c来匹配即可。
double Length[300];
Length[0]=0;
for(int i=1;i<300;i++){
Length[i]=1.0/(i+1)+Length[i-1];
}
double c;scanf("%lf",&c);
while(c!=0){
for(int i=1;i<300;i++){
if(Length[i]>=c){
printf("%d card(s)\n",i);
break;
}
}
scanf("%lf",&c);
}
优化:
当我们已经使用了记忆化数组存储的时候,上面所显示的匹配方式就显的有点傻,这不是又进行了很多重复操作吗?但另一方面,搜索又是必要的。所以我们怎么使搜索更加简化呢?答案就是二分。
我们可以利用二分,更快地查找到答案所需的n值,而这个二分写起来是并不麻烦的:
double c;scanf("%lf",&c);
while(c!=0){
int Left=1;int Right=299;
int Middle=(Left+Right)/2;
while(!(Length[Middle]>=c&&Length[Middle-1]<c)) {
if (c > Length[Middle]) Left=Middle;
else Right=Middle;
Middle = (Left + Right) / 2;
}
printf("%d card(s)\n",Middle);
scanf("%lf",&c);
}
最终代码:
#include<iostream>
using namespace std;
int main(){
double Length[300];
Length[0]=0;
for(int i=1;i<300;i++){
Length[i]=1.0/(i+1)+Length[i-1];
}
double c;scanf("%lf",&c);
while(c!=0){
int Left=1;int Right=299;
int Middle=(Left+Right)/2;
while(!(Length[Middle]>=c&&Length[Middle-1]<c)) {
if (c > Length[Middle]) Left=Middle;
else Right=Middle;
Middle = (Left + Right) / 2;
}
printf("%d card(s)\n",Middle);
scanf("%lf",&c);
}
}
总结:
这道题目的关键就是一开始的记忆化数组,以及最后的二分查找,虽然此题的数据量并不大,但是这样的优化在将来的学习中是很有用的。如果我的文章给您带来了帮助,请点赞关注哦!