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

[C++] 프로그래머스 : 단체사진찍기

by 두둠칫 2022. 6. 9.

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

 

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

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

programmers.co.kr

 

순열조합문제

 

완전탐색인지 판단과 순열조합 구현 하는게 관건이었고 본인은 완전탐색으로 판단하는게 어려웠다... 완전탐색 문제는 분류없이는 아직 판단하기가 어렵다.

순열조합을 포함해서 이 문제에 활용한 c++ library는 다음과 같다.

 

1. 순열조합 : <algorithm> : next_permutation(BidirectionalIterator first, BidirectionalIterator last, Compare comp)

조합할 컨테이너의 시작/끝 iter + 비교함수

 

2. 절대값 : <cstdlib> : abs(int a)

흔한건데 라이브러리를 매일 헷갈려서..(double과 float는 또 다르다)

 

3. 컨테이너 원소 찾기 : string : find(string a)

컨테이너 내 문자열 a의 시작 인덱스 반환

 

 

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

using namespace std;

// 전역 변수를 정의할 경우 함수 내에 초기화 코드를 꼭 작성해주세요.
int solution(int n, vector<string> data) {
    int answer = 0;
    
    string f = "ACFJMNRT";
    int diff = 0;
    
    do{
        bool res = true;
        for(int i=0; i<n; i++){
            diff = abs((int)(f.find(data[i][0]) - f.find(data[i][2]))) - 1;
            bool flag = false;
            if(
                (data[i][3] == '=' && (diff == data[i][4]-'0'))
                || (data[i][3] == '<' && (diff < data[i][4]-'0'))
                || (data[i][3] == '>' && (diff > data[i][4]-'0'))
              ){
                flag = true;
            }
            
            if(!flag)
                res = false;
        }
        
        if(res)
            answer++;
        
    } while(next_permutation(f.begin(), f.end()));
    
    return answer;
}