培养信心练手题,POJ1207 具体描述如下:
这题本质上不难,其实只需要实现一下题目中给出的算法,然后计算一下循环数,顺便开一个数组存储一下计算后的值方便以后调用即可;比较坑的一点是题目给的输入i和j可能不是按照先小后大的顺序给的,因此需要先把输入的两个数比一下大小确定哪个是上界哪个是下界,我就因为这个WA了一次,还要记得输出时i和j的顺序要和输入时的一致,代码如下:
# include <iostream>
using namespace std;
int cycle_length[10001] = { 0 };
void get_cycle_length(int num)
{
int cycle_num = 1, temp_num = num;
while (temp_num != 1)
{
if (temp_num % 2 == 0)
temp_num = temp_num / 2;
else
temp_num = temp_num * 3 + 1;
cycle_num++;
}
cycle_length[num] = cycle_num;
}
int main()
{
int lower_bound = 0, higher_bound = 0;
while (cin >> lower_bound >> higher_bound)
{
cout << lower_bound << " " << higher_bound << " ";
int longest_cycle = 0;
if (lower_bound > higher_bound)
{
int temp = lower_bound
lower_bound = higher_bound;
higher_bound = temp;
}
for (int i = lower_bound; i <= higher_bound; i++)
{
if (cycle_length[i] == 0)
get_cycle_length(i);
if (cycle_length[i] > longest_cycle)
longest_cycle = cycle_length[i];
}
cout << longest_cycle << endl;
}
return 0;
}