본문 바로가기

algorithm

[프로그래머스] - "신고 결과 받기" C++ / map

728x90

문제 링크

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

풀이과정

문제 해석

1. 각 유저는 여러번 신고당할 수 있으며, k번 이상 신고당하면 정지가 된다.

2. A 유저가 B 유저를 여러번 신고할 순 있지만, 한 번만 신고한 걸로 처리된다.

3. id_list 벡터에는 전체 유저 리스트 / report 벡터에는 누가 누구를 신고했는지가 저장되어있다.

4. id_list 벡터에 들어있는 유저 순서대로 몇명을 정지시켰는지 배열에 저장해 리턴한다.

 

풀이

map을 사용하여 "누가 몇번 신고당했는지" 기록하기 위해 reportedCnt를 생성합니다.

그리고 "누가 누구누구를 신고했는지" 기록하기 위해 reportList를 생성합니다.

 

map의 find 메소드를 활용하여 중복을 체크한 다음 첫 기록이라면 reportList, reportedCnt에 저장해줍니다.

그 다음 유저 순서대로 배열에 정답을 저장해야 하기 때문에, id_list 배열을 for문으로 돌려서 답을 저장해줬습니다.

 

코드

#include <string>
#include <set>
#include <map>
#include <vector>
using namespace std;

map < string , int > reportedCnt;
map < string , set < string > > reportList;

vector<int> solution(vector<string> id_list, vector<string> report, int k) {
	vector<int> answer;
	for(string s: report) {
        int blank = s.find(" ");
        string from = s.substr(0,blank);
        string to = s.substr(blank+1);
        
        // 신고를 중복으로 할 수 없음
        if(reportList[from].find(to) == reportList[from].end()) {
            reportList[from].insert(to);
            reportedCnt[to]++;
        }
    }
    for(string s: id_list) {
        int res = 0;
        for(string str: reportList[s]) 
            if(reportedCnt[str] >= k) res++;
        answer.push_back(res);
    }
    return answer;
}

 

728x90