水题。
看别人都说水题。。 我写了一个多小时emmmmm,最后发现是二分查找的退出条件少了个等号。。
一.描述
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.
Input
Output
Sample Input
1.00 3.71 0.04 5.19 0.00
Sample Output
3 card(s) 61 card(s) 1 card(s) 273 card(s)
二.分析
n张卡片最终会得到 1/2 + 1/3 + .... + 1/(n+1)的长度,现在反过来,给出一个长度(float)c,询问n最小是多少,才能让和项S(n)>=c
否则,返回low
四.源代码
#include
#include
int binSearch(float record[], int low, int hig, float c);
const float eps = 1e-6f;
int main()
{
using namespace std;
float record[277];
float sum = 0;
for (int n = 1; n <= 276; ++n) {
sum += 1.0f / (n+1);
record[n] = sum;
}
cin >> sum;
while (sum >= 0.01 && sum <= 5.20) {
cout << binSearch(record, 1, 276, sum) << " card(s)" << endl;
cin >> sum;
}
return 0;
}
int binSearch(float record[], int low, int hig, float c)
{
if (c <= 0.5)
return 1;
int mid = (low + hig) / 2;
while (low <= hig) {
if (c < record[mid])
hig = mid - 1;
else if (c > record[mid])
low = mid + 1;
else
break;
mid = (low + hig) / 2;
}
if (fabs(c - record[mid]) < eps)
return mid;
return low;
}