【题目来源】
http://oj.ecustacm.cn/problem.php?id=1744
http://oj.ecustacm.cn/viewnews.php?id=1023
【题目描述】
冰雹猜想是指对于任意一个正整数,如果它是奇数,则对它乘3加1,如果是偶数,则除以2,最终会变成1,目前仍未找到反例。
例如数字6。按照上述规则可以变成3、10、5、16、8、4、2、1,经过8次变换。
现在给定数字n,求存在多少个数字变换n次得到1。
【输入格式】
输入一个数字n(0≤n≤55)
【输出格式】
输出一个数字表示答案。
【输入样例】
样例1
0
样例2
4
样例3
8
【输出样例】
样例1
1
样例2
1
样例3
4
【算法分析】
本题显然用倒推,有2种情况:
(1)“除以2”的倒推,是“乘2”;
(2)“乘3加1”的倒推,是“减1除以3”,需要注意,此时应该判断“减1除以3”能除尽,而且是奇数。
【算法代码】
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int n;
LL ans=0;
void dfs(LL x,LL cnt) {
if(x==1 && cnt!=1) return;
if(cnt==n+1) {
ans++;
return;
}
dfs(2*x,cnt+1);
if((x-1)%3==0 && ((x-1)/3)%2==1)
dfs((x-1)/3,cnt+1);
}
int main() {
cin>>n;
dfs(1,1);
cout<<ans;
return 0;
}
/*
in:8
out:4
*/
【参考文献】
https://blog.csdn.net/weixin_43914593/article/details/131768564