</pre>The 3n + 1 problem</div><div class="plm" style="text-align: center;font-size:14px;"><table align="center"><tbody><tr><td><strong>Time Limit:</strong> 1000MS</td><td width="10px"> </td><td><strong>Memory Limit:</strong> 10000K</td></tr><tr><td><strong>Total Submissions:</strong> 53927</td><td width="10px"> </td><td><strong>Accepted:</strong> 17142</td></tr></tbody></table></div><p class="pst" style="font-size: 18pt; font-weight: bold; color: blue;">Description</p><div class="ptx" lang="en-US" style="font-family: 'Times New Roman', Times, serif;font-size:14px;">Problems in Computer Science are often classified as belonging to a certain class of problems (e.g., NP, Unsolvable, Recursive). In this problem you will be analyzing a property of an algorithm whose classification is not known for all possible inputs. Consider the following algorithm: <pre> 1. input n 2. print n 3. if n = 1 then STOP 4. if n is odd then n <-- 3n+1 5. else n <-- n/2 6. GOTO 2
Input
Output
Sample Input
1 10 100 200 201 210 900 1000
Sample Output
1 10 20 100 200 125 201 210 89 900 1000 174
#include <iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; int a[100010]; int main() { ios::sync_with_stdio(false); long long ans; int m,sum,n; for(int i=1; i<100010; i++) { ans=i; sum=1; while(ans!=1) { if(ans%2==1) { ans=ans*3+1; } else { ans>>=1; } sum++; } a[i]=sum; } while(cin>>n>>m) { sum=0; int flag=1; if(n>m) { flag=0; swap(n,m); //n,m的关系; } for(int i=n;i<=m;i++) { if(sum<a[i]) sum=a[i]; } if(flag) cout<<n<<" "<<m<<" "; else cout<<m<<" "<<n<<" "; cout<<sum<<endl; } return 0; }思考:n到1000000?暴力还行么?
虽然能过,但时间长;
#include <iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; int a[100010]; int main() { ios::sync_with_stdio(false); long long ans; int m,sum,n; for(int i=1; i<100010; i++) { ans=i; sum=1; while(ans!=1) { if(ans%2==1) { ans=ans*3+1; } else { ans>>=1; } sum++; if(ans<i) { sum+=a[ans]-1; //减少时间; break; } } a[i]=sum; } while(cin>>n>>m) { sum=0; int flag=1; if(n>m) { flag=0; swap(n,m); } for(int i=n;i<=m;i++) { if(sum<a[i]) sum=a[i]; } if(flag) cout<<n<<" "<<m<<" "; else cout<<m<<" "<<n<<" "; cout<<sum<<endl; } return 0; }