Блог пользователя meiniak

Автор meiniak, история, 4 года назад, По-английски

Here is the problem link and the solution. I have wrote a recusive solution with memoization to not re compute the sub-problems which have been computed. But i am getting Runtime error due to too much memory allocation in unordered map. How can i optimize it to get A.C ?

My solution :

long long recur(long long n){
    if(n==0) return 0;
    else if(memo.find(n)!=memo.end()){
        return memo[n];
    }
    else{
        long long a = n%3 == 0 ? 1 + recur(n-(2*n)/3) : INT_MAX;
        long long b = n%2 == 0 ? 1 + recur(n-(n/2)) : INT_MAX;
        long long c = 1 + recur(n-1);
        vector<long long> v = {a,b,c};
        memo[n] = *min_element(v.begin(),v.end());
        return memo[n];
    }
}
  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится
»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

I have couple of question,

  1. Is bfs sometimes can act as a more faster way than dfs ?

  2. Also,the states in dfs fashion are more intuitive as dp[n] = min(dp[n-1],dp[n/2],dp[n/3) + 1 as i did in the above solution , if i can't reach x'th state from n state i return INT_MAX.

  3. Why my solution is having stack overflow, is it due to c++ recursion limit, or my map is having 1e9 keys which is causing overlimit.

  4. Can you explain me how to define dp states if we use bfs approach

  5. What paradigm of dp it is called when using dfs or bfs .

Thank you for the kind patience. Will appreciate a lot.

  • »
    »
    4 года назад, # ^ |
    Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится
    1. The problem is that your function will visit each state from $$$0...n$$$ and since n can be up $$$10^9$$$ the function is too slow.
    2. -
    3. Visiting too many states
    4. In bfs it would be other way around, dp[x] = minimum number of steps to make x from n

    5. ???

    Btw, you can fix your dfs dp by changing it to dp[n] = min(n % 2 + recur(n / 2), n % 3 + recur(n / 3)).