넘치게 채우기

[LeetCode] 1792. Maximum Average Pass Ratio 본문

PS/LeetCode

[LeetCode] 1792. Maximum Average Pass Ratio

riveroverflow 2024. 12. 15. 15:31
728x90
반응형

https://leetcode.com/problems/maximum-average-pass-ratio/description/

leetcode - Maximum Average Pass Ratio

문제 유형: 우선순위 큐, 그리디

문제 난이도: Medium

 

문제

There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam.

You are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes.

The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes.

Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted.

 

classes[i]에는 [pass_i, total_i]가 있다. 각각 반의 합각자수, 총 학생 수이다.

반드시 통과하는 똑똑한 학생 extraStudents명이 새로 온다.

전체 반들의 합격률 평균을 최대화하시오.

 

풀이

우선순위 큐에 넣어서, 학생 한 명 추가 시 가장 크게 합격률이 오르는 순서로 넣는다.

 

우선순위 큐에서 한 반을 빼서, 실제로 1명을 추가하고(합격자+1, 전체인원+1), 다시 우선순위 큐에 넣는다.

이를 extraStudents만큼 반복하고, 평균을 내준다.

 

코드

C++

#pragma GCC optimize("O3", "unroll-loops");
static const int __ = [](){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    return 0;
}();

struct comp {
    bool operator()(const pair<int, int> &a, const pair<int, int> &b) {
        double gainA = ((double)a.first + 1) / (a.second + 1) - (double)a.first / a.second;
        double gainB = ((double)b.first + 1) / (b.second + 1) - (double)b.first / b.second;
        return gainA < gainB;
    }
};

class Solution {
public:
    double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) {
        int n = classes.size();
        priority_queue<pair<int, int>, vector<pair<int, int>>, comp> pq;

        for(auto &cls : classes) {
            pq.push({cls[0], cls[1]});
        }

        for(int i =  0; i < extraStudents; ++i) {
            auto [p, t] = pq.top();
            pq.pop();

            pq.push({p+1, t+1});
        }

        double ans = 0.0;
        while(!pq.empty()) {
            auto [p, t] = pq.top();
            pq.pop();
            ans += (double)p/t;
        }

        return ans/n;
    }
};
728x90
반응형