1 #include<iostream> 2 using namespace std; 3 4 int a[1000001]; 5 6 7 int main() 8 { 9 int n,m,max; 10 __int64 i,k; 11 int cnt ; 12 13 for(k = 1; k <= 100000; k++) 14 { 15 cnt = 0; 16 i = k; 17 while(true) 18 { 19 cnt++; 20 if(i==1) 21 break; 22 if(i%2 == 0) 23 i = i/2; 24 else 25 i = 3*i +1; 26 } 27 a[k] = cnt; 28 } 29 30 while(scanf("%d%d",&n,&m)!= EOF) 31 { 32 int tmp; 33 max = 0; 34 cout<<n<<' '<<m<<' '; 35 if(m < n) 36 { 37 tmp = n; 38 n = m; 39 m = tmp; 40 } 41 42 for(i = n; i <= m; i++) 43 { 44 if(a[i]>max) 45 max = a[i]; 46 } 47 48 49 cout<<max<<endl; 50 } 51 return 0; 52 }
时间有点慢,递归调用的话,可以零ms 下面是别人代码,甚好,所以贴来作比较。尚需努力啊————————
1 #include <stdio.h> 2 #define SIZE 10020 //SIZE开到10010都WA,10020就AC…… 3 int cycle[SIZE] = {0}; 4 int get_cycle(int n){ 5 if(n >= SIZE) return (n%2 == 1) ? get_cycle((3*n+1)/2)+2 : get_cycle(n/2)+1; //n超出SIZE范围时直接递归,避免越界 6 else if(cycle[n] == 0) cycle[n] = (n%2 == 1) ? get_cycle((3*n+1)/2)+2 : get_cycle(n/2)+1; 7 return cycle[n]; 8 } 9 int main(){ 10 int i, j, ii, jj; 11 cycle[1] = 1; 12 for(int k = 2; k < SIZE; k++) 13 get_cycle(k); 14 while(EOF != scanf("%d%d", &ii, &jj)){ 15 i = (ii < jj) ? ii : jj; 16 j = ii+jj-i; 17 int max = cycle[i]; 18 for(int k = i+1; k <= j; k++) 19 max = (cycle[k] > max) ? cycle[k] : max; 20 printf("%d %d %d\n", ii, jj, max); 21 } 22 return 0; 23 }