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