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

Автор red_coder, 12 лет назад, По-английски

suppose we are applying memoization in which we check if we have already calculated the value for some value of N. If yes we simply return that value; like if DP[N]>-1 return DP[N] else compute for N and store it in DP[N].

But how to apply memoization when N is too large upto 10^9. After all we cant have size of array DP[] upto 10^9.

  • Проголосовать: нравится
  • +14
  • Проголосовать: не нравится

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

In such situations i often memorize only first 1000000, or, if it is posible — try to memorize, for example, answers for n=1, n=1000, n=2000, ... n=1000000000, and try to write algo which calculate answers, using only this information. Hope, this trick will help you in some problems, and sorry for my poor English =)

P.s. Or, if there is no chanse to use some tricks, it means that there is another solution, which will not have TLE, and you must find it )

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

Probably You NOT need computed values for each possible value in range 1..10^9. (If yes, O(N) memory is necessary)

So, solution is simple. Store answer only for necessary values and use container like std::map. Space complexity is linear (_O(m)_, where m is a number of stored items) and time complexity of single lookup is O(lg m). This is the price, which we must pay (or take out memoisation :P).

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

    if i am not wrong basically u are pointing towards hash tables. Am i correct?

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

      Yes.

      Hash tables and fine for this purpose too. But in this case is good to know the final number of elements; in this kind of problem this is often hard to guess.

      Using of red-black tree instead MAY be better.

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

        dude i dont know even a single thing about how to implement hashing and red-black trees in code. Can u give some link of tutorial or code by which i can learn it. Its scary :(

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

when i used vector< pair<int,int> > for hashing then for larger values of N it gave runtime error. Pls somebody help