관리 메뉴

Mini

프로그래머스 모의고사 c++ // 완전탐색 본문

Algorithm/완전탐색

프로그래머스 모의고사 c++ // 완전탐색

Mini_96 2023. 10. 12. 16:38

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

 

프로그래머스

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

programmers.co.kr

1. 내코드

1.1 배열을각각 채우고

1.2 일치하는 갯수 카운팅

1.3 최대값과 일치하면 정답에 푸쉬

#include <bits/stdc++.h>

using namespace std;

int arr1[10004]={1,2,3,4,5}, arr2[10004]={2,1,2,3,2,4,2,5},arr3[10004]={3,3,1,1,2,2,4,4,5,5};
int cnt1,cnt2,cnt3;

vector<int> solution(vector<int> answers) {
    vector<int> answer;
    
    int start=0;
    for(int i=5;i<=10000;++i){
        arr1[i]=arr1[start%5];
        start++;
    }
    
    start=0;
    for(int i=8;i<=10000;++i){
        arr2[i]=arr2[start%8];
        start++;
    }
    
    start=0;
    for(int i=10;i<=10000;++i){
        arr3[i]=arr3[start%10];
        start++;
    }
    
    for(int i=0;i<answers.size();++i){
        if(answers[i]==arr1[i]) cnt1++;
        if(answers[i]==arr2[i]) cnt2++;
        if(answers[i]==arr3[i]) cnt3++;
    }
    
    //cout<<cnt1<<" "<<cnt2<<" "<<cnt3;
    
    int max_1=0;
    max_1=cnt1;
    max_1=max(max_1,cnt2);
    max_1=max(max_1,cnt3);
    
    if(max_1==cnt1){
        answer.push_back(1);
    }
    if(max_1==cnt2){
        answer.push_back(2);
    }
    if(max_1==cnt3){
        answer.push_back(3);
    }
    
    return answer;
}

 

2.  모법답안

2.1 배열을 직접 채울필요없이 인덱스%size하면 패턴만 접근가능하다.

2.2 cnt를 백터에 담은후 max_element를 이용해 한번에 최대값을 찾을 수 있다. 

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

using namespace std;

vector<int> one = {1,2,3,4,5};
vector<int> two = {2,1,2,3,2,4,2,5};
vector<int> thr = {3,3,1,1,2,2,4,4,5,5};

vector<int> solution(vector<int> answers) {
    vector<int> answer;
    vector<int> they(3);
    for(int i=0; i<answers.size(); i++) {
        if(answers[i] == one[i%one.size()]) they[0]++;
        if(answers[i] == two[i%two.size()]) they[1]++;
        if(answers[i] == thr[i%thr.size()]) they[2]++;
    }
    int they_max = *max_element(they.begin(),they.end());
    for(int i = 0; i< 3; i++) {
        if(they[i] == they_max) answer.push_back(i+1);
    }
    return answer;
}