GitHubSeob

C++ / 프로그래머스 / 신고 결과 받기 본문

Programmers/Level 1

C++ / 프로그래머스 / 신고 결과 받기

GitHubSeob 2022. 3. 8.

문제

https://programmers.co.kr/learn/courses/30/lessons/92334

 

코딩테스트 연습 - 신고 결과 받기

문제 설명 신입사원 무지는 게시판 불량 이용자를 신고하고 처리 결과를 메일로 발송하는 시스템을 개발하려 합니다. 무지가 개발하려는 시스템은 다음과 같습니다. 각 유저는 한 번에 한 명의

programmers.co.kr

문제풀이

unordered_map을 이용하여 <string, int> 형태로 신고당한 ID, 신고당한 횟수인 report_cnt

<string, int> 형태로 신고한 ID, 정지 먹인 횟수인 reporter_cnt를 선언한다.

먼저 erase, unique를 이용하여 중복 신고 내역을 없앤다. (동일한 유저에 대한 신고 횟수는 1회로 처리되므로)

 

    for (idx = 0; idx < report.size(); ++idx) {
        blank_idx = report[idx].find(" ") + 1;
        report_cnt[report[idx].substr(blank_idx)]++;
    }

그다음 report 내역을 신고한 유저 ID, 신고당한 유저 ID로 나누기 위해 substr을 이용한다.

공백을 기준으로 앞은 신고한 유저ID, 뒤는 신고당한 유저 ID이다.

신고당한 횟수를 먼저 구해야 하므로 report[신고당한 유저 ID]에 횟수를 1씩 더한다.

 

    for (idx = 0; idx < report.size(); ++idx) {
        blank_idx = report[idx].find(" ") + 1;
        if (report_cnt[report[idx].substr(blank_idx)] >= k) {
            reporter_cnt[report[idx].substr(0, blank_idx - 1)]++;
        }
    }

그다음 정지를 먹인 횟수를 구한다.

위와 같이 공백을 기준으로 나눈다.

report[신고당한 유저 ID] 횟수가 k이상일 경우 reporter_cnt[신고한 유저 ID]에 1을 더한다.

 

    for (idx = 0; idx < id_list.size(); ++idx) {
        answer.push_back(reporter_cnt[id_list[idx]]);
    }

vector <int> answer을 return 해야 하므로 reporter_cnt값을 push 한다.

 

 

 

코드

#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>

using namespace std;

vector<int> solution(vector<string> id_list, vector<string> report, int k) {
    vector<int> answer;
    unordered_map <string, int> report_cnt;
    unordered_map <string, int> reporter_cnt;
    sort(report.begin(), report.end());
    report.erase(unique(report.begin(), report.end()), report.end());
    
    int idx(0);
    int blank_idx(0);

    for (idx = 0; idx < report.size(); ++idx) {
        blank_idx = report[idx].find(" ") + 1;
        report_cnt[report[idx].substr(blank_idx)]++;
    }
    for (idx = 0; idx < report.size(); ++idx) {
        blank_idx = report[idx].find(" ") + 1;
        if (report_cnt[report[idx].substr(blank_idx)] >= k) {
            reporter_cnt[report[idx].substr(0, blank_idx - 1)]++;
        }
    }
    for (idx = 0; idx < id_list.size(); ++idx) {
        answer.push_back(reporter_cnt[id_list[idx]]);
    }

    return answer;
}