简体   繁体   中英

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 ie 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?

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM