-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchampagne_tower.cpp
More file actions
57 lines (53 loc) · 1.48 KB
/
champagne_tower.cpp
File metadata and controls
57 lines (53 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
* =====================================================================================
*
* Filename: champagne_tower.cpp
*
* Description: 799. Champagne Tower.
*
* Version: 1.0
* Created: 09/24/2023 15:11:09
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <algorithm>
#include <tuple>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using std::tuple;
using std::vector;
// Dynamic programming
class Solution {
public:
double champagneTower(int poured, int query_row, int query_glass) {
vector<vector<double>> flows(101, vector<double>(101));
flows[0][0] = static_cast<double>(poured);
for (int r = 0; r <= query_row; ++r) {
for (int c = 0; c <= r; c++) {
const double q = (flows[r][c] - 1.0) / 2.0;
if (q > 0) {
flows[r + 1][c] += q;
flows[r + 1][c + 1] += q;
}
}
}
return std::min(1.0, flows[query_row][query_glass]);
}
};
TEST(Solution, champagneTower) {
vector<tuple<int, int, int, double>> cases = {
std::make_tuple(1, 1, 1, 0.0),
std::make_tuple(2, 1, 1, 0.5),
std::make_tuple(100000009, 33, 17, 1.0),
};
for (auto& c : cases) {
EXPECT_EQ(Solution().champagneTower(std::get<0>(c), std::get<1>(c), std::get<2>(c)),
std::get<3>(c));
}
}