[WXM] LeetCode 808. Soup Servings C++

808. Soup Servings

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.

Notes:

  • 0 <= N <= 10^9.
  • Answers within 10^-6 of the true value will be accepted as correct.

Approach

  1. 题目大意初始你有N毫升的两水杯A和B,然后有四种操作减少两水杯中的水,A中先没水的概率是多少,两个同时没水算一半。这道题数据特别大,但是这个数据使用来唬人的,因为你可以发现这概率是不断上升的,因为四种操作有三个都是操作A比较多,所以概率只会随着数据不断上升,所以达到程度的时候就返回1就可以了,这个临界值大约为4800,但是用记忆化搜索,还是开不到这么大的数组,所以我们还要收缩数据,我们把数据都收缩25倍(刚好可以整除四种操作,减少误差),这样就足够开了。

Code

class Solution {
public:
    double DFS(int a, int b, vector<vector<double>>&cache) {
        if (a <= 0 && b <= 0)return 0.5;
        if (a <= 0)return 1;
        if (b <= 0)return 0;
        if (cache[a][b] != -1)return cache[a][b];
        cache[a][b] = 0.25*(DFS(a - 4, b, cache) + DFS(a - 3, b - 1, cache) + DFS(a - 2, b - 2, cache) + DFS(a - 1, b - 3, cache));
        return cache[a][b];
    }
    double soupServings(int N) {
        if (N == 0)return 0.5;
        if (N >= 5000)return 1;
         N = ceil(N / 25.0);
        vector<vector<double>>cache(N+1, vector<double>(N+1, -1));
        return DFS(N, N, cache);
    }
};

猜你喜欢

转载自blog.csdn.net/WX_ming/article/details/82178652