猴子吃桃问题
来源:互联网 发布:有意思的书推荐 知乎 编辑:程序博客网 时间:2024/05/18 00:24
猴子吃桃问题
时间限制:3000 ms | 内存限制:65535 KB
难度:0
- 描述
- 有一堆桃子不知数目,猴子第一天吃掉一半,又多吃了一个,第二天照此方法,吃掉剩下桃子的一半又多一个,天天如此,到第m天早上,猴子发现只剩一只桃子了,问这堆桃子原来有多少个? (m<29)
- 输入
- 第一行有一个整数n,表示有n组测试数据(从第二行开始,每一行的数据为:第m天);
- 输出
- 每一行数据是桃子的总个数
- 样例输入
2311
- 样例输出
226142
- 来源
- 网络
- 上传者
首席执行官
问题分析:
将整个事件从时间上倒过来看:
第一天 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函数来对应一一关系。
阅读全文
0 0
- 猴子吃桃问题
- 猴子吃桃问题
- 猴子吃桃问题
- 猴子吃桃问题
- 猴子吃桃问题
- 猴子吃桃问题
- 猴子吃桃问题
- 猴子吃桃问题
- 猴子吃桃问题
- 猴子吃桃问题
- 猴子吃桃问题
- 猴子吃桃问题
- 猴子吃桃问题
- 猴子吃桃问题
- 猴子吃桃问题
- 猴子吃桃问题
- 猴子吃桃问题
- 猴子吃桃问题
- MongoDB数据库查询方法
- django 数据库的用户名和密码错了,这样改
- Volley源码学习笔记_Request
- jmeter碰到的问题及解决方案
- 低电量自动关机时无关机动画
- 猴子吃桃问题
- 事件触发器---dispatchEvent
- HTML5 之图片上传预处理
- BZOJ4598: [Sdoi2016]模式字符串
- ubuntu使用mailx利用SMTP发送邮件
- Hadoop(HDFS、YARN、HBase、Hive和Spark等)默认端口表
- yuy
- 问题 Q(1208): 【基础算法】倒酒问题
- 责任链模式及其在web容器中的应用