본문 바로가기

코딩테스트 연습/programmers

[Programmers] 프로그래머스 단체사진 찍기(c++)

https://programmers.co.kr/learn/courses/30/lessons/1835

 

코딩테스트 연습 - 단체사진 찍기

단체사진 찍기 가을을 맞아 카카오프렌즈는 단체로 소풍을 떠났다. 즐거운 시간을 보내고 마지막에 단체사진을 찍기 위해 카메라 앞에 일렬로 나란히 섰다. 그런데 각자가 원하는 배치가 모두

programmers.co.kr

코딩테스트 연습 < 2017 카카오코드 본선 < 단체사진 찍기

 

 

문제풀이 팁💡

{A, C, F, J, M, N, R, T} 를 하나씩 순열을 세워서, 문제에서 주어진 data의 모든 조건을 통과하는 순열만 answer++ 한다.

 

1. <algorithm>헤더에 들어있는 next_permutation함수를 사용하여 friends에 대한 순열을 하나씩 뽑아낸다.

2. 뽑아낸 순열을 data의 조건에 부합하는지 확인하고, 하나라도 맞지 않으면 break해서 다시 1번으로 돌아간다.

3. 만약 2번에서 data의 모든 조건에 부합한다면, if(k+1 == data.size())조건문으로 넘어가서 answer+1 해준다.

4. answer 개수를 출력한다.

 

 

 


main포함 코드(c++)

#include <string>
#include <vector>
#include <cstdlib>
#include <algorithm>
using namespace std;


void Permnutation(vector<char> arr, vector<string> data, int &answer)
{
    do{
        string text = "";
        for(int j=0;j<arr.size();j++)text+=arr[j];
        for(int k=0;k<data.size();k++){
            string first = data[k].substr(0,1);
            string third = data[k].substr(2,1);
            int term = stoi(data[k].substr(4,1));
            
            int first_position = text.find(first);
            int third_position = text.find(third);

            if(data[k].substr(3,1) == ">"){
                if(abs(first_position - third_position)-1 <= term) break;
            }
            else if(data[k].substr(3,1) == "<"){
                if(abs(first_position - third_position)-1 >= term) break;
            }
            else if(data[k].substr(3,1) == "="){
                if(abs(first_position - third_position)-1 != term) break;
            }
            
            if(k+1 == data.size())answer++; //모든 조건 다 통과하면 +1개
        }
    }
    while(next_permutation(arr.begin(),arr.end()));
}

int solution(int n, vector<string> data) {
    int answer = 0;
   
    vector<char> friends = {'A', 'C', 'F', 'J', 'M', 'N', 'R', 'T'};
    Permnutation(friends, data, answer);
    
    return answer;
}

int main()
{

    int n = 2;
    vector<string> data = {"N~F=0", "R~T>2"};
//    vector<string> data = {"M~C<2", "C~M>1"};
    
    solution(n, data);
    
    return 0;
}

 

 

후기✍️

처음에 조합으로 풀었는데,  반복문이 한번밖에 실행되지 않아서 다시 확인해보니 순열 문제였다. (순서를 신경써야하는 문제)
do-while문을 사용하지 않고 while문을 사용해서 제출했는데, 답이 틀려서 뭔지 고민해보니,
맨 처음의 조건 {A, C, F, J, M, N, R, T} 에 대한 순열을 건너뛰게되어서 그런거였다.