Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

Life Engineering

[프로그래머스] 단체사진 찍기 (C++) 본문

Problem Solving

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

흑개 2021. 9. 16. 19:28

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

 

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

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

programmers.co.kr

 

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

using namespace std;

int solution(int n, vector<string> data) {
    int answer = 0;
    vector<char> v={'A', 'C', 'F', 'J', 'M', 'N', 'R', 'T'};
    do{
        vector<char> temp;
        vector<char>::iterator it1;
        vector<char>::iterator it2;
        bool flag=true;
        for (auto it=v.begin(); it!=v.end(); it++){
            temp.push_back(*it);
        }
        for (string s : data){
            int me=s[0];
            int you=s[2];
            it1=find(temp.begin(), temp.end(), me);           //조건 불만족, flag=false 후 break
            it2=find(temp.begin(), temp.end(), you);
            if (s[3]=='='){
                if ((abs(it1-it2)-1)!=(s[4]-'0')){       
                    flag=false;
                    break;
                }
            }
            else if (s[3]=='<'){
                if ((abs(it1-it2)-1)>=(s[4]-'0')){
                    flag=false;
                    break;
                }
            }
            else{ 
                if ((abs(it1-it2)-1)<=(s[4]-'0')){
                    flag=false;
                    break;
                }
            }
        }
        if (flag){
            answer++;
        }
        
    } while (next_permutation(v.begin(), v.end()));
    return answer;
}

처음엔 막막했다.. 확률과 통계 문제 푸는 것처럼 해야하나? 

했는데.. 잘 생각해보니 답은 완전탐색이었다. (8!=40320 이므로 완전탐색 완전 가능이다)

 

가능한 모든 순열을 탐색하고, 그 순열 중에 조건을 만족하는 애들만 세주면 된다.

 

me와 friend의 index를 찾은 후에 둘 간의 거리가 조건들을 모두 만족하면(하나라도 조건 만족하지 못하면 flag값을 false 를 주고, 조건을 따져보는 반복문을 탈출한다) answer++ 을 해주면 된다.

 

순열을 구할 땐 next_permutation 함수를 사용한다.

 

그런데 애초에 temp에 순열을 안 넣어줘도 된다.. v 로 그대로 진행해도 ok 다.

그리고 find 할 때 temp.begin() 이 부분 안넣어줘도 된다.. 그냥 찾고자 하는 문자만 넣어주면 ok다.

=,<,> 에 따라 if..else 로 하지 말고 차라리 함수로 따로 빼준다.

 

bool isRight(int diff, int dist, char c) 해줘서, diff가 dist 와 일치하면 c에 따라 (diff<dist, diff==dist, diff>dist ) 이런 식으로 해줘서 조건을 만족하면 true를 리턴하게 해주는 방식이 더 깔끔하다.