Can anyone please explain how this problem can be solved in top-down manner (Recursive dp).
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | Dominater069 | 154 |
8 | awoo | 154 |
10 | luogu_official | 150 |
Can anyone please explain how this problem can be solved in top-down manner (Recursive dp).
Название |
---|
Check the following implementation for small values of $$$K$$$ and $$$a_i$$$.
Candies
Thanks for you help!
Let dp[i][j] represent how many ways possible to distribute exactly j candies among first i participants. so dp[i][j]=dp[i-1][j]+dp[i-1][j-1]+dp[i-1][j-2]........+dp[i-1][j-a[i]].
Calculating this sum if you are using loop will lead to O(n*k*k)
So you prefix sum instead . This prefix sum can be the dp array itself or another 2d array
Implementataion:
Using dp as prefix array only:
here and below is the main part
using another 2d array to store prefix sums: here
I was looking for a recursive solution, thanks nonetheless.
let $$$dp[i][j]$$$ = the number of ways to share $$$j$$$ candies among the remaining kids. We can write a $$$O(K * K * N)$$$ DP:
However, this is too slow and will result in TLE. To optimize this, let's calculate all possible states starting from the $$$(i + 1)$$$-th kid before calculating any state starting from the $$$i$$$-th kid. We can see that $$$dp[i][j]$$$ = ($$$dp[i + 1][j]$$$ + $$$dp[i + 1][j - 1]$$$ + ... + $$$dp[i + 1][j - limit]$$$), limit is $$$min(j, a[i])$$$. If we store the prefix sum of states starting from the $$$(i + 1)$$$-th kid, we can compute the DP transition in $$$O(1)$$$ and reduce the complexity to $$$O(K * N)$$$.
Submission: Link
Thanks! got it now
thanks bro really nice solution ,, i was searching for this solution for around 2 hrs
thanks alot bro