본문 바로가기
알고리즘/알고리즘

[C++] 프로그래머스 : 할인 행사

by 두둠칫 2022. 10. 30.

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

 

프로그래머스

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

programmers.co.kr

 

map 사용해서 비교하는 문제

비교 구현 방식을 수정하면서 코드를 더 정제화할 수 있었다

 

1. map 2개 사용, map iterator 포인터 사용

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

using namespace std;

int solution(vector<string> want, vector<int> number, vector<string> discount) {
    int answer = 0;
    
    map<string, int> wm, sm;
    for(int i=0; i<want.size(); i++){
        wm.insert(make_pair(want[i], number[i]));
    }
    for(int i=0; i<9; i++){
        map<string,int>::iterator it = sm.find(discount[i]);
        if(it == sm.end()){
            sm.insert(make_pair(discount[i], 1));
        }
        else{
            (it->second)++;
        }
    }
    
    for(int i=9; i<discount.size(); i++){
        map<string,int>::iterator it = sm.find(discount[i]);
        if(it == sm.end()){
            sm.insert(make_pair(discount[i], 1));
        }
        else{
            (it->second)++;
        }
        
        bool same = true;
        for(auto m : wm){
            if(m.second != (sm.find(m.first))->second){
                same = false;
                break;
            }
        }
        if(same) answer++;
        
        it = sm.find(discount[i-9]);
        if(it->second == 1){
            sm.erase(it->first);
        }
        else{
            (it->second)--;
        }
    }
    
    
    return answer;
}

2. map 2개 사용, map iterator 포인터 사용X

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

using namespace std;

int solution(vector<string> want, vector<int> number, vector<string> discount) {
    int answer = 0;
    
    map<string, int> wm, sm;
    for(int i=0; i<want.size(); i++){
        wm[want[i]] = number[i];
    }
    for(int i=0; i<9; i++){
        sm[discount[i]]++;
    }
    
    for(int i=9; i<discount.size(); i++){
        sm[discount[i]]++;
        
        bool same = true;
        for(auto m : wm){
            if(m.second != sm[m.first]){
                same = false;
                break;
            }
        }
        if(same) answer++;
        
        sm[discount[i-9]]--;
    }
    
    
    return answer;
}

3. map 1개 사용

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

using namespace std;

int solution(vector<string> want, vector<int> number, vector<string> discount) {
    int answer = 0;
    
    map<string, int> sm;
    for(int i=0; i<9; i++){
        sm[discount[i]]++;
    }
    
    for(int i=9; i<discount.size(); i++){
        sm[discount[i]]++;
        
        bool same = true;
        for(int j=0; j<want.size(); j++){
            if(sm[want[j]] != number[j]){
                same = false;
                break;
            }
        }
        if(same) answer++;
        
        sm[discount[i-9]]--;
    }
    
    
    return answer;
}