알고리즘/programmers

[Programmers 코딩테스트 고득점 Kit] 위장

꾸준함. 2021. 9. 21. 00:31

문제 링크입니다: https://programmers.co.kr/learn/courses/30/lessons/42578

 

코딩테스트 연습 - 위장

 

programmers.co.kr

해쉬와 조합을 이용하는 문제였습니다.

 

알고리즘은 아래와 같습니다.

1. map을 이용하여 의상 타입을 int로 변환하고 각 의상 타입이 몇 개씩 있는지 파악합니다.

2. 결과를 구하기 위해서는 조합 공식을 써야하는데 해당 공식은 (의상 타입1 + 1) * (의상 타입 2 + 1) *... * (의상 타입 N + 1) - 1입니다.

3. 위 조합 공식을 이용해 답을 구하고 반환해줍니다.

 

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
const int MAX = 30;
vector<string> clothTypes[MAX];
int solution(vector<vector<string>> clothes) {
map<string, int> clothType2idx;
int idx = 0;
for (int i = 0; i < clothes.size(); i++)
{
string cloth = clothes[i][0];
string type = clothes[i][1];
if (!clothType2idx.count(type))
{
clothType2idx[type] = idx++;
}
clothTypes[clothType2idx[type]].push_back(cloth);
}
int answer = 1;
for (int i = 0; i < idx; i++)
{
answer *= (clothTypes[i].size() + 1);
}
return answer - 1;
}
int main(void)
{
vector<vector<string>> clothes = {
{ "yellowhat", "headgear" },
{ "bluesunglasses", "eyewear" },
{ "green_turban", "headgear" }
};
cout << solution(clothes) << "\n";
return 0;
}
view raw .cpp hosted with ❤ by GitHub

 

개발환경:Visual Studio 2017

지적, 조언, 질문 환영입니다! 댓글 남겨주세요~

반응형