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

Автор adarsh851997, история, 6 лет назад, По-английски

here is one of the dp question in which i got stucked ;please someone help me . i know there are many geneious people here for whom this problem will be a cakewalk.

PROBLEM:: A rat gives birth to 2 rat on day 1 and on day 2 it gives birth to 3 rat and on third day it dies. how many rats will be present at Nth day .intially there are K rats are present; k and n are upto 1e4;

MY SOLUTION here is what i did i tried to calcualte number od rats present on day i,let it be dp[i].

so,dp[i]=number of rats on (i-1) day+number of rats on (i-2) day + (birth on (i-1) day)*2 + (birth on (i-2) day)*3 -death on i-3 th day; is iam right? or something is wrong the problem was asked in interview of airtel and the interviewer was not satisfied.

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

»
6 лет назад, скрыть # |
 
Проголосовать: нравится +11 Проголосовать: не нравится

Your DP has a problem: it doesn't take into consideration the rats' age. I mean, when you calculate dp[i], how do you precisely know how many rats from the previous days give birth to 2 babies and how many to 3? The correct solution is the following: let dp[i][j] be the number of rats who are alive on the i-th day and are j days old (j is either 1 or 2). The final answer will be dp[n][1] + dp[n][2]. The recurrence relation is:

dp[1][1] = K
dp[1][2] = 0
dp[i][1] = dp[i-1][1]*2 + dp[i-1][2]*3
dp[i][2] = dp[i-1][1], for all i from 2 to N.

Note that this DP does take into consideration the rats' 3-day lifespan: from dp[i][2] you can only go to dp[i+1][1]. In other words, the rats that are two days old only contribute to the answer with the babies they make.