猜数字(HDU-2178)

xiaoxiao2021-02-28  61

Problem Description

    A有一个数m,B来猜。B每猜一次,A就说太大、太小或对了。

    问B猜n次可以猜到的最大数。

Input

    第1行是整数T,表示有T组数据,下面有T行

    每行一个整数n (1 ≤ n ≤ 30) 

Output

     猜n次可以猜到的最大数

Sample Input

    2

    1     3

Sample Output

    1     7

思路:

题意:有1~m的数,最多猜n次,一定能猜到(1,m)内的任意数

    设:能找到最大的数为M

    则:左边界:1,右边界:M,每次查找左端不变右端加一,查找n次得到足够大的数

    故:

     第一次查找:(M+1)/2=M,得:M=1

        第二次查找:( (M+1)/2+M+1 )/2=M,得:M=3

        第三次查找:( (M+1)/2+M+1 )/2+M+1 )/2=M,得:M=7

        第四次查找:( ( (M+1)/2+M+1 )/2+M+1 ) +M+1)/2=M,得:M=15

        第五次查找:( ( ( (M+1)/2+M+1 )/2+M+1 ) +M+1)/2 )/2=M,得:M=31

数学归纳法,得:M=2^n-1

    因此:利用公式直接计算得结果

Source Program

#include<cstdio> #include<cmath> int main() { int t; int n; int total; scanf("%d",&t);//输入测试数据个数 while(t--) { scanf("%d",&n);//输入猜的次数 total=pow(2,n)-1; printf("%d\n",total);//输出可猜出的最大值 } return 0; }
转载请注明原文地址: https://www.6miu.com/read-2631764.html

最新回复(0)