[프로그래머스]level-2 next_permutation 를 사용한 단체 사진찍기

이준규·2022년 4월 7일
0

알고리즘

목록 보기
6/7

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

n 개 원소의 순열을 구할 수 있는 algorithm헤더의 next_permutation() 를 사용해서 풀 수 있는 문제라서 정리를 해봄

next_permutation() 사용법

  • include <algorithm>

next_permutation() 는 오름차순 으로 정렬되어있는 컨테이너를 다음 순열의 형태로 바꾸면서 더이상 순열이 존재하지 않으면 false 를 반환 한다.

기본적으로 do .. while 과 함께 사용

do {
	//....
} while (next_permutation(s.begin(), s.end()));

반드시 s 는 오름차순 정렬되어야함 (문자열도 마찬가지)

출처) https://mjmjmj98.tistory.com/38

문제풀이

  • 이문제에서는 카카오친구들을 문자열로 오름차순 저장한다.
    string str = "ACFJMNRT";
  • next_permutation 를 위의 예시 처럼 사용하여 각 순열을 돌면서 각자의 거리를 구해서 비교체크 해주면 끝.
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

bool check(string str, char f, char s, char d, int dist) {
    int a = str.find(f) - str.find(s);
    int distance = abs(a) - 1;
    
    if (d == '=') {
        return distance == dist;
    }
    else if (d == '>') {
        return distance > dist;
    }
    else {
        return distance < dist;
    }
}

// 전역 변수를 정의할 경우 함수 내에 초기화 코드를 꼭 작성해주세요.
int solution(int n, vector<string> data) {
    int answer = 0;
    string str = "ACFJMNRT";
    
    do {
        bool flag = true;
        for (string s : data) {
            char first = s[0];
            char second = s[2];
            char diff = s[3];
            int dist = s[4] - '0';
            
            if (!check(str, first, second, diff, dist)) {
                flag = false;
                break;
            }
        }
        if (flag) answer++;
    } while (next_permutation(str.begin(), str.end()));
    
    return answer;
}
  • check는 data 의 각 조건을 통과하는지 체크해주는 함수
  • 조건을 전부 통과하면 그 순열을 answer++;
profile
백엔드

0개의 댓글