uva100:3n+1
My Submissions
# | | Problem | Verdict | Language | Run Time | Submission Date |
8227717 | 100 | The 3n + 1 problem | Accepted | C++ | 0.388 | 2010-09-04 14:05:13 |
8227694 | 100 | The 3n + 1 problem | Runtime error | C++ | 0.000 | 2010-09-04 13:49:50 |
这是我第一次去UVA做题,没想到开头来个RE呜呜.....
此题大概意思看懂了,是说给你闭区间让你求出最长的3n+1长度,3n+1操作是说你个数如果是奇数则将这个数扩大3倍后再加1,如果是偶数则将这个数除以2,直到这个数为1停止;所谓长度则是从n到1一共产生了多少个数包括n和1;比如3产生的数有10,5,16,8,4,2,1所以3的长度就是7;
题目要求输出这个闭区间最大的长度;以下是原题目的链接;
以下是我AC的代码:
代码
1 #include <iostream>
2 #include <cstdio>
3 #include <cstring>
4 #include <algorithm>
5
6 using namespace std;
7
8 const int ARRLEN = 1000001;
9 int a, s, b, e;
10 char flag[ARRLEN];//标记给定区间在所产生的序列中是否出现过
11
12 int getstep(int n)
13 {
14 int total = 1;
15
16 while( n > 1 ){
17 if( n & 1){
18 n = (n << 1) + n + 1;
19 }
20 else{
21 n >>= 1;
22 }
23 if( n <= b && n >= a)//如果当前产生的数是在给定的区间中则标记
24 flag[n] = 0;
25 total++;
26 }
27
28 return total;
29 }
30
31 int main()
32 {
33 int res;
34
35 while( scanf("%d%d", &a, &b) != EOF ){
36 s = a; e = b;
37 if(a > b){
38 swap(a, b);
39 }
40 res = 0;
41 memset(flag+a, 1, b-a+1);
42 for(int i=b, temp; i>=a; i--){
43 if( !flag[i] ){
44 continue;
45 }
46 temp = getstep(i);
47 if(temp > res){
48 res = temp;
49 }
50 }
51 printf("%d %d %d\n", s, e, res);
52 }
53
54 return 0;
55 }
56
2 #include <cstdio>
3 #include <cstring>
4 #include <algorithm>
5
6 using namespace std;
7
8 const int ARRLEN = 1000001;
9 int a, s, b, e;
10 char flag[ARRLEN];//标记给定区间在所产生的序列中是否出现过
11
12 int getstep(int n)
13 {
14 int total = 1;
15
16 while( n > 1 ){
17 if( n & 1){
18 n = (n << 1) + n + 1;
19 }
20 else{
21 n >>= 1;
22 }
23 if( n <= b && n >= a)//如果当前产生的数是在给定的区间中则标记
24 flag[n] = 0;
25 total++;
26 }
27
28 return total;
29 }
30
31 int main()
32 {
33 int res;
34
35 while( scanf("%d%d", &a, &b) != EOF ){
36 s = a; e = b;
37 if(a > b){
38 swap(a, b);
39 }
40 res = 0;
41 memset(flag+a, 1, b-a+1);
42 for(int i=b, temp; i>=a; i--){
43 if( !flag[i] ){
44 continue;
45 }
46 temp = getstep(i);
47 if(temp > res){
48 res = temp;
49 }
50 }
51 printf("%d %d %d\n", s, e, res);
52 }
53
54 return 0;
55 }
56
posted on 2010-09-04 22:38 geniusgogo 阅读(444) 评论(0) 编辑 收藏 举报