Programmers/LV1

프로그래머스 실패율 c++

Hun-bot 2024. 11. 8. 17:52
728x90
반응형

초기 시도 코드 [실패]

map을 사용하려다가 귀찮아질 것 같아서 vector의 pair 사용법에 대해서 배웠다

https://www.geeksforgeeks.org/how-to-create-vector-of-pairs-in-cpp/

 

How to Create a Vector of Pairs in C++? - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

bool compare(const pair<int, double>& a, const pair<int, double>& b) {
    if (a.second == b.second) {
        return a.first < b.first;
    }
    return a.second > b.second;  
}

vector<int> solution(int N, vector<int> stages) {
    vector<int> answer;
    vector<pair<int, double>> failed; 

    int total_user = stages.size();

    for (int i = 1; i <= N; i++) {
        int stage = count(stages.begin(), stages.end(), i);
        double fail_rate = static_cast<double>(stage) / total_user;
        failed.push_back({i, fail_rate});
        total_user -= stage;
    }

    sort(failed.begin(), failed.end(),compare);

    for (const auto& p : failed) {
        answer.push_back(p.first);
    }

    return answer;
}

2차 시도 [통과]

다른 건 문제가 없는데 전체 사용자가 줄어들었을 때, 1미만으로 떨어지는 경우를 생각하지 않아서 틀린것 같았다.

for부분에 fail_rate에서 삼항연산자를 통해 간단하게 구현했고 통과했다.

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

bool compare(const pair<int, double>& a, const pair<int, double>& b) {
    if (a.second == b.second) {
        return a.first < b.first;
    }
    return a.second > b.second;  
}

vector<int> solution(int N, vector<int> stages) {
    vector<int> answer;
    vector<pair<int, double>> failed; 

    int total_user = stages.size();

    for (int i = 1; i <= N; i++) {
        int stage = count(stages.begin(), stages.end(), i);
        double fail_rate = (total_user > 0) ? static_cast<double>(stage) / total_user : 0.0;
        failed.push_back({i, fail_rate});
        total_user -= stage;
    }

    sort(failed.begin(), failed.end(),compare);

    for (const auto& p : failed) {
        answer.push_back(p.first);
    }

    return answer;
}
728x90
반응형