[POJ1207]The 3n+1 Problem
水题,练手
但是会有一些题目没给出的信息,容易找不出bug
1、输入的i,j没有顺序,需要先排序
2、输出的i,j需要按原顺序输出
1 #include<iostream> 2 using namespace std; 3 4 int ans[100000000]; //all value is 0 5 6 int compute(int n) 7 { 8 if (ans[n] != 0) return ans[n]; 9 if (n % 2 == 1) 10 { 11 ans[n] = compute(3 * n + 1) + 1; 12 } 13 else 14 { 15 ans[n] = compute(n / 2) + 1; 16 } 17 return ans[n]; 18 } 19 20 int max(int i, int j) 21 { 22 int mx = 0; 23 int iter = i; 24 while (iter <= j) 25 { 26 if (mx < ans[iter]) 27 mx = ans[iter]; 28 iter++; 29 } 30 return mx; 31 } 32 33 int main() 34 { 35 ans[1] = 1; 36 37 int i, j, x, y; //x,y is used to output 38 while (cin >> i >> j) 39 { 40 x = i, y = j; 41 42 if (i > j) 43 { 44 int t = i; 45 i = j; 46 j = t; 47 } 48 49 int iter = i; 50 while (iter <= j) 51 { 52 compute(iter); 53 iter++; 54 } 55 56 cout << x << " " << y << " " << max(i, j) << endl; 57 } 58 return 0; 59 }