猴子吃桃问题

xiaoxiao2021-02-28  50

猴子吃桃问题

时间限制: 3000 ms  |  内存限制: 65535 KB 难度: 0 描述 有一堆桃子不知数目,猴子第一天吃掉一半,又多吃了一个,第二天照此方法,吃掉剩下桃子的一半又多一个,天天如此,到第m天早上,猴子发现只剩一只桃子了,问这堆桃子原来有多少个? (m<29) 输入 第一行有一个整数n,表示有n组测试数据(从第二行开始,每一行的数据为:第m天); 输出 每一行数据是桃子的总个数 样例输入 2 3 11 样例输出 22 6142 来源 网络 上传者

首席执行官

问题分析:

将整个事件从时间上倒过来看:

第一天  0个 第二天 1个 第三天 (1+1)*2 =4 第四天 (4+1)*2=10 第五天 (10+1)*2=22个  依次类推,直到第29天。

代码:

#include <iostream> #include <stdio.h> #include <string.h> #include <math.h> #include <vector> #include <queue> #include <stack> #include <map> #include <string> #include <algorithm> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int num[30]; void init(){ num[1]=1; for(int i=2;i<=29;i++){ num[i]=(num[i-1]+1)*2; } } int main(int argc, char** argv) { init(); int n; scanf("%d",&n); while(n--){ int x; scanf("%d",&x); printf("%d\n",num[x+1]); } return 0; }优秀代码:

01. #include<stdio.h> 02. int main() 03. { 04. int n,m; 05. scanf("%d",&n); 06. while(n--) 07. { 08. scanf("%d",&m); 09. printf("%d\n",(3<<m)-2); 10. } 11. return 0; 12. } 对比分析:

优秀代码厉害了!看不懂呀!3<<m 其中<<为左移运算符。结果分析第一天  0个 第二天 1个 第三天 (1+1)*2 =4 第四天 (4+1)*2=10 第五天 (10+1)*2=22个  依次类推,直到第29天的映射关系刚好可以用(3<<m )-2来映射其对应关系。

但这种程序除了在oj上有用写到实际工程上可以说是毫无可度性。

    收获:优秀代码中相当于用了一个hash函数来对应一一关系。

转载请注明原文地址: https://www.6miu.com/read-85781.html

最新回复(0)