프로그래머스/카카오

[프로그래머스/Level 3/C++/2019 카카오 개발자 겨울 인턴십] 불량 사용자

Vfly 2023. 1. 28. 22:45

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

- 출처 : 프로그래머스 코딩 테스트 연습

 

프로그래머스

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

programmers.co.kr

 

[문제 요약]

- 개발팀 내에서 이벤트 개발을 담당하고 있는 "무지"는 최근 진행된 카카오이모티콘 이벤트에 비정상적인 방법으로 당첨을 시도한 응모자들을 발견하였습니다.

 

- 이런 응모자들을 따로 모아 불량 사용자라는 이름으로 목록을 만들어서 당첨 처리 시 제외하도록 이벤트 당첨자 담당자인 "프로도" 에게 전달하려고 합니다.

 

- 이 때 개인정보 보호을 위해 사용자 아이디 중 일부 문자를 '*' 문자로 가려서 전달했습니다.

 

- 가리고자 하는 문자 하나에 '*' 문자 하나를 사용하였고 아이디 당 최소 하나 이상의 '*' 문자를 사용하였습니다.


- "무지"와 "프로도"는 불량 사용자 목록에 매핑된 응모자 아이디를 제재 아이디 라고 부르기로 하였습니다.

예를 들어, 이벤트에 응모한 전체 사용자 아이디 목록이 다음과 같다면

다음과 같이 불량 사용자 아이디 목록이 전달된 경우,

불량 사용자에 매핑되어 당첨에서 제외되어야 야 할 제재 아이디 목록은 다음과 같이 두 가지 경우가 있을 수 있습니다.

- 이벤트 응모자 아이디 목록이 담긴 배열 user_id와 불량 사용자 아이디 목록이 담긴 배열 banned_id가 매개변수로 주어질 때, 당첨에서 제외되어야 할 제재 아이디 목록은 몇가지 경우의 수가 가능한 지 return 하도록 solution 함수를 완성해주세요.

 

[문제 조건]

  • user_id 배열의 크기는 1 이상 8 이하입니다.
  • user_id 배열 각 원소들의 값은 길이가 1 이상 8 이하인 문자열입니다.
    • 응모한 사용자 아이디들은 서로 중복되지 않습니다.
    • 응모한 사용자 아이디는 알파벳 소문자와 숫자로만으로 구성되어 있습니다.
  • banned_id 배열의 크기는 1 이상 user_id 배열의 크기 이하입니다.
  • banned_id 배열 각 원소들의 값은 길이가 1 이상 8 이하인 문자열입니다.
    • 불량 사용자 아이디는 알파벳 소문자와 숫자, 가리기 위한 문자 '*' 로만 이루어져 있습니다.
    • 불량 사용자 아이디는 '*' 문자를 하나 이상 포함하고 있습니다.
    • 불량 사용자 아이디 하나는 응모자 아이디 중 하나에 해당하고 같은 응모자 아이디가 중복해서 제재 아이디 목록에 들어가는 경우는 없습니다.
  • 제재 아이디 목록들을 구했을 때 아이디들이 나열된 순서와 관계없이 아이디 목록의 내용이 동일하다면 같은 것으로 처리하여 하나로 세면 됩니다.

 

[문제 풀이]

문제 자체는 어렵지 않은 문제였지만, 중복 처리를 어떻게 하느냐에 따라 체감상 난이도가 달랐던거 같다.

 

처음에 필자는 map자료 구조를 이용하여 banned_id에 해당하는 user_id를 찾아서 개별로 저장하는 방식을 사용했다.

void find(map<string,vector<string>> &mp, vector<string> &user_id, string ban_id)
{
    for(int i=0; i<user_id.size(); i++)
    {
        if(user_id[i].size() == ban_id.size())
        {
            bool flag = true;
            for(int k=0; k<ban_id.size(); k++)
            {
                if(ban_id[k] == '*') continue;

                if(ban_id[k] != user_id[i][k]) {flag = false; break;}
            }
            if(flag) mp[ban_id].push_back(user_id[i]);
        }
    }
}
//////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////
for(int i=0; i<banned_id.size(); i++) 
{
    if(mp.find(banned_id[i]) != mp.end()) continue;
    find(mp, user_id, banned_id[i]);
}

find 함수는 banned_id의 원소별로 user_id에 찾아서 map 자료구조에 저장하는 함수다.

 

그 다음 DFS 방식을 이용하여 불량 사용자들의 순열을 찾았고, 찾아진 순열에서 중복을 제거하는 방법으로는 set자료구조를 사용하였다.

void dfs(int cur, int depth, set<vector<string>> &st, map<string,vector<string>> &mp, map<string, bool>  &ck, vector<string> &banned_id)
{
    if(depth == banned_id.size())
    {
        vector<string> tmp2 = tmp;
        sort(tmp2.begin(), tmp2.end());
        st.insert(tmp2);
        return;
    }

    for(int i=0; i<mp[banned_id[cur]].size(); i++)
    {
        string next = mp[banned_id[cur]][i];
        if(ck[next]) continue;
        ck[next] = true;
        tmp.push_back(next);
        dfs(cur+1, depth+1, st, mp, ck, banned_id);
        ck[next] = false;
        tmp.pop_back();
    }
}

순차적으로 탐색하면서 해당하는 문자열을 tmp배열에 넣어주고, 만약의 탐색 깊이가 banned_id배열의 크기와 같아지는 순간 set에 배열을 정렬하여 추가하였다.

 

여기서 중요한 점은 순열을 이용할 경우 set에 정렬해서 넣어야 중복을 제대로 제거 할 수 있다.

 

[소스 코드1]

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

using namespace std;

int answer;
vector<string> tmp;

void find(map<string,vector<string>> &mp, vector<string> &user_id, string ban_id)
{
    for(int i=0; i<user_id.size(); i++)
    {
        if(user_id[i].size() == ban_id.size())
        {
            bool flag = true;
            for(int k=0; k<ban_id.size(); k++)
            {
                if(ban_id[k] == '*') continue;

                if(ban_id[k] != user_id[i][k]) {flag = false; break;}
            }
            if(flag) mp[ban_id].push_back(user_id[i]);
        }
    }
}

void dfs(int cur, int depth, set<vector<string>> &st, map<string,vector<string>> &mp, map<string, bool>  &ck, vector<string> &banned_id)
{
    if(depth == banned_id.size())
    {
        vector<string> tmp2 = tmp;
        sort(tmp2.begin(), tmp2.end());
        st.insert(tmp2);
        return;
    }

    for(int i=0; i<mp[banned_id[cur]].size(); i++)
    {
        string next = mp[banned_id[cur]][i];
        if(ck[next]) continue;
        ck[next] = true;
        tmp.push_back(next);
        dfs(cur+1, depth+1, st, mp, ck, banned_id);
        ck[next] = false;
        tmp.pop_back();
    }
}

int solution(vector<string> user_id, vector<string> banned_id) {
    answer = 0;

    map<string,vector<string>> mp;
    map<string, bool> ck;
    set<vector<string>> st;

    for(int i=0; i<banned_id.size(); i++) 
    {
        if(mp.find(banned_id[i]) != mp.end()) continue;
        find(mp, user_id, banned_id[i]);
    }

    dfs(0,0,st,mp,ck,banned_id);

    answer = st.size();
    return answer;
}

 

다음으로 소개할 코드는 chatgpt라는 openAPI를 이용하여 위의 코드를 최적화 시킨 코드인데 아래 코드도 정답으로 처리가 된다.

 

[소스 코드2]

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

using namespace std;

int answer = 0;

void dfs(int cur, int depth, set<vector<string>> &st, vector<string> &user_id, vector<string> &banned_id, vector<int> &matched) {
    if (depth == banned_id.size()) {
        vector<string> temp;
        for (int i : matched) temp.push_back(user_id[i]);
        sort(temp.begin(), temp.end());
        st.insert(temp);
        return;
    }

    for (int i = 0; i < user_id.size(); i++) {
        if (user_id[i].size() != banned_id[cur].size()) continue;

        bool match = true;
        for (int k = 0; k < banned_id[cur].size(); k++) {
            if (banned_id[cur][k] == '*') continue;
            if (banned_id[cur][k] != user_id[i][k]) { match = false; break; }
        }
        if (!match) continue;

        if (find(matched.begin(), matched.end(), i) != matched.end()) continue;
        matched.push_back(i);
        dfs(cur + 1, depth + 1, st, user_id, banned_id, matched);
        matched.pop_back();
    }
}

int solution(vector<string> user_id, vector<string> banned_id) {
    set<vector<string>> st;
    vector<int> matched;
    dfs(0, 0, st, user_id, banned_id, matched);
    return st.size();
}

위의 코드는 현재 불량이용자 아이디의 목록의 해당되는 아이디를 user_id에서 찾은 뒤 그 id의 index를 matched라는 배열에 넣어주고, matched의 크기가 banned_id배열의 크기와 같아졌을때 set에 추가하는 방식을 이용했다.

 

중복여부는 기존에 있던 find함수를 이용하여 전에 사용되었는지 여부를 판별한다.