[HDOJ]1032. The 3n + 1 problem
不是很难的问题,但有两个问题,一大一小需要注意一下:
大的问题是,看到这个题目,应该可以知道,对不每组不同的输入,会有些数据可以重复利用的,比如对于输入1 10和5 15来说,重复部分是5和10之间的数据。
也就是说,我们在处理每组数据时,不必要对每组的数据逐一处理,聪明的做法就是预先整一个大的数组,把我们所需要的所有的数据存下来,用的话直接去取就可以了。这样可以避免大量重复的计算。
小的问题就是,对于这种输入中有范围的数,注意一下,它并不是跟你想象中的那样,把小的放在前面,大的放在后面,这个需要额外的判断一下,如果不是的话,就swap一下。不过说实话,这种测试数据真的很无聊的说。
Code如下:
1
#include <iostream>
2
using namespace std;
3
#define MAXNUM 1000000 + 1
4
int result[MAXNUM];
5
int main()
6
{
7
int beg,end,max,count,temp;
8
while(cin>>beg>>end)
9
{
10
cout<<beg<<" "<<end<<" ";
11
if(beg > end)
12
{
13
temp = beg;beg = end;end = temp;
14
}
15
max = count = 0;
16
for(int t = beg;t <= end;++t)
17
{
18
if(result[t])
19
count = result[t];
20
else
21
{
22
temp = t;
23
count = 1;
24
while(temp != 1)
25
{
26
if(temp%2 == 0)
27
temp = temp/2;
28
else
29
temp = 3*temp + 1;
30
++count;
31
}
32
result[t] = count;
33
}
34
if(count > max)
35
max = count;
36
}
37
cout<<max<<endl;
38
}
39
return 0;
40
}
#include <iostream>2
using namespace std;3
#define MAXNUM 1000000 + 14
int result[MAXNUM];5
int main()6
{7
int beg,end,max,count,temp;8
while(cin>>beg>>end)9
{10
cout<<beg<<" "<<end<<" ";11
if(beg > end)12
{13
temp = beg;beg = end;end = temp;14
}15
max = count = 0;16
for(int t = beg;t <= end;++t)17
{18
if(result[t])19
count = result[t];20
else21
{22
temp = t;23
count = 1;24
while(temp != 1)25
{26
if(temp%2 == 0)27
temp = temp/2;28
else29
temp = 3*temp + 1;30
++count;31
}32
result[t] = count;33
}34
if(count > max)35
max = count;36
}37
cout<<max<<endl;38
}39
return 0;40
}
我没有什么雄心壮志,我只想给自己和关心自己的家人和朋友一个交代,仅此而已。


浙公网安备 33010602011771号