这道橙题也太水了吧!直接模拟输出流程就可以了!
老规矩,先看题目。
这题让我们寻找输入的每对(i,j)中[i,j]内所有数字区间长度的max值。我们可以用模拟递推对[i,j]内所有的数进行相同的操作。
操作流程如下:
想必看了流程图,思路就更清晰了。但别忘了,我们求的是数n的周期长度即操作次数,所以我们在编写period函数时要加上计数器count。
以下就是period函数的代码了:
1 int period(int x){//period函数对数x进行操作 2 int count=1;//计数器初始化为1,程序至少输出一次(原始)x 3 while(x!=1){//如果x不为1,继续对x进行操作 4 if(x%2) x=x*3+1;//x为奇数时,其值为3x+1 5 else x/=2;//否则x为偶数时,其值为x/2 6 count++;//每执行一次操作,操作次数+1 7 } 8 return count;//返回操作次数 9 }
写好函数代码以后,用for循环对每对[i,j]区间内的数执行period操作,再用maxn记录区间内操作数的最大值即可。
那么以下就是AC代码!
代码
(注释版)
1 #include<bits/stdc++.h>//万能头文件 2 using namespace std; 3 int i,j; 4 int period(int x){//period函数对数x进行操作 5 int count=1;//计数器初始化为1,程序至少输出一次(原始)x 6 while(x!=1){//如果x不为1,继续对x进行操作 7 if(x%2) x=x*3+1;//x为奇数时,其值为3x+1 8 else x/=2;//否则x为偶数时,其值为x/2 9 count++;//每执行一次操作,操作次数+1 10 } 11 return count;//返回操作次数 12 } 13 int main(){//好习惯,程序从主函数读起 14 while(cin>>i>>j){//while不断读入i,j,直到程序结束 15 int maxn=0;//求最大值要初始化为0 16 for(int a=min(i,j);a<=max(i,j);a++)//a从i,j中较小的开始,遍历整个区间内所有整数 17 maxn=max(maxn,period(a));//最大值为此次操作次数和之前操作次数中的最大值 18 cout<<i<<" "<<j<<" "<<maxn<<endl;//输出时别忘了换行endl 19 } 20 return 0;//返回值为0 21 }
(无注释版)
1 #include<bits/stdc++.h> 2 using namespace std; 3 int i,j; 4 int period(int x){ 5 int count=1; 6 while(x!=1){ 7 if(x%2) x=x*3+1; 8 else x/=2; 9 count++; 10 } 11 return count; 12 } 13 int main(){ 14 while(cin>>i>>j){ 15 int maxn=0; 16 for(int a=min(i,j);a<=max(i,j);a++) 17 maxn=max(maxn,period(a)); 18 cout<<i<<" "<<j<<" "<<maxn<<endl; 19 } 20 return 0; 21 }
总结
1. while(cin>>i>>j): 读入每对 (i,j)(i,j) 直至无可读取信息。
2. 在比较最大值和最小值时,记录最大值、最小值的变量要初始化为最小数和最大数。
3. 碰到一些无思路的操作流程题,建议先模拟递推寻找思路。