|
1 | 1 | //go:build ignore |
2 | 2 | #include "cpp/common/Solution.h" |
3 | | - |
| 3 | +#include <queue> |
4 | 4 |
|
5 | 5 | using namespace std; |
6 | 6 | using json = nlohmann::json; |
7 | 7 |
|
| 8 | +struct Tp { |
| 9 | + double improvement; |
| 10 | + int pass; |
| 11 | + int total; |
| 12 | + Tp(double imp, int p, int t) : improvement(imp), pass(p), total(t) {} |
| 13 | + bool operator<(const Tp &other) const { |
| 14 | + return improvement < other.improvement; |
| 15 | + } |
| 16 | +}; |
| 17 | + |
8 | 18 | class Solution { |
9 | 19 | public: |
10 | | - double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) { |
11 | | - |
| 20 | + double maxAverageRatio(const vector<vector<int>> &classes, |
| 21 | + int extraStudents) { |
| 22 | + priority_queue<Tp> pq; |
| 23 | + for (const auto &c : classes) { |
| 24 | + int pass = c[0], total = c[1]; |
| 25 | + double imp = static_cast<double>(pass + 1) / (total + 1) - static_cast<double>(pass) / total; |
| 26 | + pq.emplace(imp, pass, total); |
| 27 | + } |
| 28 | + while (extraStudents-- > 0) { |
| 29 | + auto [_, pass, total] = pq.top(); |
| 30 | + pq.pop(); |
| 31 | + pass++; |
| 32 | + total++; |
| 33 | + double imp = static_cast<double>(pass + 1) / (total + 1) - static_cast<double>(pass) / total; |
| 34 | + pq.emplace(imp, pass, total); |
| 35 | + } |
| 36 | + double result = 0.0; |
| 37 | + while (!pq.empty()) { |
| 38 | + auto [_, pass, total] = pq.top(); |
| 39 | + pq.pop(); |
| 40 | + result += static_cast<double>(pass) / total; |
12 | 41 | } |
| 42 | + return result / classes.size(); |
| 43 | + } |
13 | 44 | }; |
14 | 45 |
|
15 | 46 | json leetcode::qubh::Solve(string input_json_values) { |
16 | | - vector<string> inputArray; |
17 | | - size_t pos = input_json_values.find('\n'); |
18 | | - while (pos != string::npos) { |
19 | | - inputArray.push_back(input_json_values.substr(0, pos)); |
20 | | - input_json_values = input_json_values.substr(pos + 1); |
21 | | - pos = input_json_values.find('\n'); |
22 | | - } |
23 | | - inputArray.push_back(input_json_values); |
| 47 | + vector<string> inputArray; |
| 48 | + size_t pos = input_json_values.find('\n'); |
| 49 | + while (pos != string::npos) { |
| 50 | + inputArray.push_back(input_json_values.substr(0, pos)); |
| 51 | + input_json_values = input_json_values.substr(pos + 1); |
| 52 | + pos = input_json_values.find('\n'); |
| 53 | + } |
| 54 | + inputArray.push_back(input_json_values); |
24 | 55 |
|
25 | | - Solution solution; |
26 | | - vector<vector<int>> classes = json::parse(inputArray.at(0)); |
27 | | - int extraStudents = json::parse(inputArray.at(1)); |
28 | | - return solution.maxAverageRatio(classes, extraStudents); |
| 56 | + Solution solution; |
| 57 | + vector<vector<int>> classes = json::parse(inputArray.at(0)); |
| 58 | + int extraStudents = json::parse(inputArray.at(1)); |
| 59 | + return solution.maxAverageRatio(classes, extraStudents); |
29 | 60 | } |
0 commit comments