猴子吃桃问题

猴子吃桃问题

时间限制: 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函数来对应一一关系。




  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值