mr_dot_convict

14-Longest Collatz sequence-ProjectEuler-mr.convict

Jun 22nd, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.26 KB | None | 0 0
  1. /*author* Priyanshu Shrivastav (from IIT Palakkad) *
  2.  * *_ __ ___  _ ______ ___  _ ____   ___  ___| |_  *
  3.  * | '_ ` _ \| '__/ __/ _ \| '_ \ \ / / |/ __| __| *
  4.  * | | | | | | | | (_| (_) | | | \ V /| | (__| |_  *
  5.  * |_| |_| |_|_|(_)___\___/|_| |_|\_/ |_|\___|\__| *
  6. When I wrote this, only God and I understood what I was doing
  7.  ** * * * * * * * Now, only God knows * * * * * * */
  8. #include         <bits/stdc++.h>
  9. using namespace std;
  10. #pragma GCC      optimize ("Ofast")
  11. #pragma GCC      optimize ("unroll-loops")
  12. #pragma GCC      target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
  13.  
  14. #define IOS      ios_base::sync_with_stdio(false); cin.tie (nullptr)
  15. #define PREC     cout.precision (10); cout << fixed
  16. #define bg(x)    " [ " << #x << " : " << (x) << " ]"
  17. #define x        first
  18. #define y        second
  19.  
  20. #define debug(args...) { \
  21.    string _s = #args; replace(_s.begin(), _s.end(), ',', ' ');\
  22.    stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); \
  23. }
  24. void err(istream_iterator<string> it) { it->empty();
  25.    cerr << " (Line : " << __LINE__ << ") " << '\n';
  26. }
  27. template<typename T, typename... Args>
  28. void err(istream_iterator<string> it, T a, Args... args) {
  29.     cerr << " [ " <<  *it << " : " << a  << " ] "<< ' ';
  30.     err(++it, args...);
  31. }
  32.  
  33. const int N = (int)5e6 + 10;
  34. int dp[N + 1], memo[N + 1];
  35.  
  36. int solve(long long n) {
  37.    if (n <= N) {
  38.       if (n == 1) return 0;
  39.       if (memo[n] != -1) return memo[n];
  40.       if (n & 1) return memo[n] = solve(3*n + 1) + 1;
  41.       else return memo[n] = solve(n/2) + 1;
  42.    }
  43.    else {
  44.       int ctr = 0;
  45.       while (n > N) {
  46.          if (n & 1) n = 3*n + 1;
  47.          else n = n/2;
  48.          ++ctr;
  49.       }
  50.       return ctr + solve(n);
  51.    }
  52. }
  53.  
  54. void precalc() {
  55.    for (int i = 1; i <= N; ++i) memo[i] = -1;
  56.  
  57.    int cur_max = 0;
  58.    for (int i = 1; i <= N; ++i) {
  59.       if (memo[i] == -1) memo[i] = solve(i);
  60.       if (i == 1) dp[i] = i;
  61.       else {
  62.          if (memo[i] >= cur_max) {
  63.             dp[i] = i;
  64.             cur_max = memo[i];
  65.          }
  66.          else dp[i] = dp[i - 1];
  67.       }
  68.    }
  69. }
  70.  
  71. signed main() {
  72.    IOS; PREC;
  73.    precalc();
  74.    int tc; cin >> tc;
  75.    while (tc--) {
  76.       int n; cin >> n;
  77.       cout << dp[n] << '\n';
  78.    }
  79.    return EXIT_SUCCESS;
  80. }
Add Comment
Please, Sign In to add comment