HDU-3750-Guess Game

HDU-3750-Guess Game

            Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Problem Description
Bob plays the “guess the number right” with Alice recently,the game’s rule is that Alice give Bob a upper limit number N ,then he write any of a number on paper which Bob can’t know what it is and the number must be between 1 and N.Bob has many chances to guess the number and every time when Bob guesses Alice will tell him if his is bigger than the correct number or small than the correct number until he is right.
Now the Bob wanted to use binary search method to guess the right number, because he knows this method is quite fast to find the right number.

Input
We test the problem in many cases.Each case begin with one integers N( 1<= N <= 100000 ).

Output
Output the expected number of chances required to guess the number right, which accurate to 2 fractional digits.

Sample Input
2
3

Sample Output
1.50
1.67

题目链接:HDU-3750

题目大意:猜数字,给出一个数字在[1,n]范围内,Bob采用二分的方法猜,问才对的期望

题目思路:每个数字的可能性为1/n,所以只要求出猜到第i个数字需要几次记为xi,把(x1 + x2 + x3 + …..xn)* 1 / n 就是答案。可用递归求出各个xi

以下是代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <cstring>
#include <algorithm>
#include <string>
#include <set>
#include <functional>
#include <numeric>
#include <sstream>
#include <stack>
#include <map>
#include <queue>
#include<iomanip>

using namespace std;
typedef long long ll;
int mp[100005];
void solve(int l,int r,int pos)
{
    if (l > r) return;
    if (l == r)
    {
          if (mp[l] == 0) mp[l] = pos;
          return;
    }
    int mid = (l + r) / 2;
    mp[mid] = pos;
    pos++;
    solve(l,mid - 1,pos);
    solve(mid + 1,r,pos);
}
int main()
{
    int n;
    double ret;
    while (cin >> n) {
          memset(mp,0,sizeof(mp));
          ret = 1.0 / n;
          solve(1,n,1);
          long long ans = 0;
          for (int i = 1; i <= n; i++)
          {
              ans += mp[i];
          }
          printf("%.2f\n",ans * ret);
    }
    return 0;
}

你可能感兴趣的:(HDU-3750-Guess Game)