Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not able to understand a dp solution

The problem is as follows:

Lazer Tag consists of a group play, where you are assigned a fixed number of bullets (popularly known as Laser shots) during the whole game. Each right shoot on your target enemy, gives you one point.

Consider the series of your hits and misses which can be represented in the form of “x” and “o” where “o” represents a hit and “x” represents a miss. Suppose the series is of the form “xxxoooxxxxooxxo”, then your final score will be equal to 3^2 + 2^2 +1^2 i.e add up the squares of every maximal number of consecutive hits in the entire game play.

The probability of hitting the jth shot correctly (1≤j≤n) is P(j). In simpler terms, the probability of getting an “o” in the series at jth turn is P(j). You need to calculate the expected score at the end of your round.

I can understand a O(n^2) solution of this using memoization but the question requires a O(n) solution. I have seen the O(n) solution but I am not able to understand it. The O(n) solution is as follows:

for(i = 1; i <= n; i++)
    dp[i] = (dp[i-1] + p[i-1]) * p[i];   
for(i = 1; i <= n; i++)
    ans+=2 * dp[i] + p[i];

where p[i] is the prob of hitting ith target. Can anyone explain how the O(n) solution works?

like image 956
SHB Avatar asked Oct 03 '22 13:10

SHB


1 Answers

You can think of the scoring in the following way:

  1. 1 point for each hit
  2. 2 points for EVERY run of hits of length >1 (scoring overlapping runs multiple times)

For example, a sequence of xxooox would score:

  1. +1 for each of the o's
  2. +2 for ooo
  3. +2 for first oo
  4. +2 for second oo

Score = 1*3+2*3 = 3+6 = 9 points. (This matches the original way of score because 9=3*3)

dp[i] computes the expected number of runs of length >1 that end at position i.

So to compute the total expected score we need to sum 2*dp[i] (as we get 2 points for every run), plus the sum of p[i] to add the expected score from getting 1 point for each hit.

The recurrence relation is because the expected number of runs of length >1 ending at position i will be:

  1. +1 if we have a new run starting at position i by getting a hit at i and i-1 (probability p[i]*p[i-1])
  2. +dp[i-1] if we continue the runs ending at position i-1 by getting another hit (probability p[i])
like image 166
Peter de Rivaz Avatar answered Oct 13 '22 11:10

Peter de Rivaz