司马杭电!大家注意测试数据,第一个不一定比第二个小。害得我调了一小时。
The 3n + 1 problem
#include <iostream> #include <cstdio> typedef long long ll; using namespace std; const int N = 1000001; int len[N]; int length(int n){ if(len[n])return len[n]; int count = 1; int pn = n; while(n!=1){ if(n%2==1)n = 3*n+1; else n = n/2; if(n<N&&len[n]){ count+=len[n]; break; } count++; } return len[pn] = count; } void swap(int& a,int& b){ int temp = a; a = b; b = temp; } int main(){ int a,b; ll max; while(cin>>a>>b){ cout<<a<<" "<<b<<" "; if(a>b)swap(a,b); max = length(a); for(int i = a+1;i<=b;++i){ if(length(i)>max)max = length(i); } cout<<max<<endl; } return 0; }