🍞 Problem Solving/Programmers

[프로그래머스][Level1] 신고 결과 받기 c++

박빵이 2022. 9. 3. 13:59

풀이과정

풀이 (시간초과 1개)

#include <string>
#include <vector>
#include <map>

using namespace std;

vector<int> solution(vector<string> id_list, vector<string> report, int k) {
    vector<int> answer;

    map<pair<string, string>, int> repo; // report
    map<string, int> s; // 신고받은 유저

    for(int i = 0; i < report.size(); i++){
        int idx = report[i].find(' ');
        string from = report[i].substr(0, idx);
        string to = report[i].substr(idx);

        repo[{from, to}]++;
        if(repo[{from, to}] == 1) s[to]++;
    }
    vector<string> v; // 정지받은 유저
    for(auto iter : s){
        if(iter.second >= k) v.push_back(iter.first);
    }

    map<string, int> ans;
    for(int i = 0; i < v.size(); i++){
        for(auto iter : repo){
            if(iter.first.second == v[i]){
                ans[iter.first.first]++;
            }
        }
    }
    for(int i = 0; i < id_list.size(); i++){
        int cnt = 0;
        for(auto iter : ans){
            if(id_list[i] == iter.first){
                answer.push_back(iter.second);
                cnt++;
            }
        }
        if(!cnt) answer.push_back(0);
    }
    return answer;
}

 

풀이 (시간초과 2개)

#include <string>
#include <vector>
#include <map>

using namespace std;

vector<int> solution(vector<string> id_list, vector<string> report, int k) {
    vector<int> answer;

    vector<vector<string>> repo;
    for(int i = 0; i < report.size(); i++){
        string str = "";
        vector<string> temp;
        for(int j = 0; j < report[i].size(); j++){
            if(report[i][j] == ' '){
                temp.push_back(str);
                str = "";
            }
            else str += report[i][j];
        }
        if(str != "") temp.push_back(str);
        repo.push_back(temp);
    }

    map<pair<string, string>, int> m; // m -> f, 1
    map<string, int> s; // 신고 받은 횟수
    for(int i = 0; i < repo.size(); i++){
        m[{repo[i][0], repo[i][1]}]++;
        if(m[{repo[i][0], repo[i][1]}] == 1){
            s[repo[i][1]]++;
        }
    }

    vector<string> v; // 정지된 유저
    for(auto i : s){
        if(i.second >= k)  v.push_back(i.first);
    }

    for(int i = 0; i < id_list.size(); i++){
        int cnt = 0;
        for(auto iter : m){
            if(id_list[i] == iter.first.first){
                for(int j = 0; j < v.size(); j++){
                    if(v[j] == iter.first.second){
                        cnt++;
                    }
                }
            }
        }
        answer.push_back(cnt);
    }
    return answer;
}