[leetcode]Soup Servings
链接:https://leetcode.com/problems/soup-servings/description/
Question
There are two types of soup: type A and type B. Initially we have N
ml of each type of soup. There are four kinds of operations:
- Serve 100 ml of soup A and 0 ml of soup B
- Serve 75 ml of soup A and 25 ml of soup B
- Serve 50 ml of soup A and 50 ml of soup B
- Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml’s of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Note:
0 <= N <= 10^9
.- Answers within
10^-6
of the true value will be accepted as correct.
Solution
class Solution {
public:
#define offset 150
int direction[4][2] = {
{4, 0},
{3, 1},
{2, 2},
{1, 3}
};
double soupServings(int N) {
if (N >= 4800) return 1;
N = (N+24)/25;
vector<vector<double>> dp;
dp.resize(N+offset+1);
for (int i = 0; i <= N+offset; i++) dp[i].resize(N+offset+1, 0);
dp[N+offset][N+offset] = 1;
double cnt = 0;
for (int i = N; i >= 1; i--) {
for (int j = N; j >= 1; j--) {
for (int k = 0; k < 4; k++) {
int x = i-direction[k][0];
int y = j-direction[k][1];
// 由于一种方式的来源可能有多种,所以必须!!要累加(调了1个多小时才发现)
dp[x+offset][y+offset] += 0.25*dp[i+offset][j+offset];
}
}
}
for (int i = 1; i <= offset; i++)
for (int j = 1+offset; j <= N+offset; j++)
cnt += dp[i][j];
for (int i = 1; i <= offset; i++)
for (int j = 1; j <= offset; j++)
cnt += 0.5*dp[i][j];
dp.clear();
return cnt;
}
};
思路:动态规划解决,特别注意的是这里的(x,y)是(i,j)的前面状态而不是后面状态。因为知道的时候最后的结果,往前推。需要注意的是,记得累加。。。