How to solve this question asked in premium coding contest?

不打扰是莪最后的温柔 提交于 2020-08-19 05:49:48

问题


Could someone guide me on how to solve this programming question? It seems something like DP problem which I couldn't find answer for.

Question:

There are ‘n’ ads. Each ad has an effectiveness value associated with it which is given in an array of size ‘n’ in the format [v1, v2, …, vn], where ‘v1’ is the effectiveness value of the first ad, ‘v2’ is the effectiveness value of the second ad, and so on. The show in which these ads will be shown is ‘m’ length long (starting from 0 till m), and the time when the ads can be shown is given in the format [(a1, b1), (a2, b2), …, (an, bn)], where ith tuple in the array denotes the timing of the ith ad in the format (start_time, end_time). Note that any ‘ai’ and ‘bi’ cannot be smaller than 0 and cannot be larger than ‘m’. When you choose to show an ad, you cannot show another ad within 4 minutes of it’s end. So if you select to show the ad having timings as (2, 4), then you cannot show another ad before 9, hence next ad cannot be (8, 10), but it can be (9, 12). You have to select the ads to show to the audience such that you maximize the sum of the effectiveness values of the ads, given the above constraints. For example, if ‘m’ is 20, and the timings of the ads are [(2, 3), (6, 9), (10, 12), (12, 13), (14, 17)] and the effectiveness values are [3, 9, 10, 6, 7], then you can show ad 2 and ad 5 (one-based-indexing) and have an effectiveness value of 16, which is the maximum you can get given the constraints.


回答1:


Your problem can be reduced to the following, let's consider 1d segments that can be described as (start_i, end_i, value_i).

Let S = array of available 1d segments

What we want is to find the non-intersecting segments that sum to the maximum possible value and fit in the interval [0, m] ( show length )

Let DP[x] = best achievable value to cover the segment [0, x] with a subset of the available 1d segments.

The recurrence relation is, given an element (s_i, e_i, v_i) we can select it or not.

DP[e_i] = DP[e_i - 1]

DP[e_i] = max( DP[e_i], DP[s_i - 1] + v_i )

dp[0] = 0;
// sort the events by increasing e_i, because
// we want to process first the events that finish earlier

for( int END = 1; END <= m; ++END)
{
    dp[end] = dp[end - 1];
    for( each ELEMENT(s_i, e_i, v_u) with (e_i == END) )
    {
        dp[end] = max( dp[end], dp[s_i - 1] + v_i ) 
    }
}


来源:https://stackoverflow.com/questions/58260448/how-to-solve-this-question-asked-in-premium-coding-contest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!