프로그래머스/2레벨

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

Koalitsiya 2024. 3. 12. 21:13
 

프로그래머스

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

programmers.co.kr

 

  • 프렌즈들이 줄을 서는 모든 경우의 수 중 data의 조건들을 충족하는 것들을 찾아야 함
  • 순열을 통해 모든 경우의 수를 만들고 각 경우의 수마다 조건을 충족하는지 체크
  • 순열 사용 시 사용할 컨테이너는 오름차순으로 정렬되어 있어야함

 

옛날 문제라 그런진 모르겠지만 정답률에 비해 난이도가 쉬웠던 문제

 

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

using namespace std;

bool conditionCheck(char oper, int nowDist, int conDist) {
    // 주어진 조건이 = 일 때 
    if(oper == '=') return nowDist == conDist;
    // 주어진 연산자가 > 일 때
    else if(oper == '>') return nowDist > conDist;
    // 주어진 연산자가 < 일 때
    else return nowDist < conDist;
}

// 전역 변수를 정의할 경우 함수 내에 초기화 코드를 꼭 작성해주세요.
int solution(int n, vector<string> data) {
    int answer = 0;
    
    string friends = "ACFJMNRT";
    
    sort(friends.begin(), friends.end());
    
    do {
        bool isCorrect = true;
        
        for(int i = 0; i < data.size(); i++) {
            // 조건을 제시한 프렌즈
            int idx1 = friends.find(data[i][0]);
            // 상대방
            int idx2 = friends.find(data[i][2]);
            // 제시자와 상대방 간의 현재 거리
            int nowDist = abs(idx1 - idx2) - 1;
            // 조건 거리
            int conDist = data[i][4] - '0';
            
            if(conditionCheck(data[i][3], nowDist, conDist)) continue;
            else { 
                isCorrect = false;
                break;   
            }
        }
        
        // 조건 만족하면 answer++
        if(isCorrect) answer++;
        
    } while(next_permutation(friends.begin(), friends.end())); // 순열
    
    return answer;
}