분류: 백트래킹, 조합 /
문제
문제 설명
바로 어제 최백준 조교가 방 열쇠를 주머니에 넣은 채 깜빡하고 서울로 가 버리는 황당한 상황에 직면한 조교들은, 702호에 새로운 보안 시스템을 설치하기로 하였다. 이 보안 시스템은 열쇠가 아닌 암호로 동작하게 되어 있는 시스템이다.
암호는 서로 다른 L개의 알파벳 소문자들로 구성되며 최소 한 개의 모음(a, e, i, o, u)과 최소 두 개의 자음으로 구성되어 있다고 알려져 있다. 또한 정렬된 문자열을 선호하는 조교들의 성향으로 미루어 보아 암호를 이루는 알파벳이 암호에서 증가하는 순서로 배열되었을 것이라고 추측된다. 즉, abc는 가능성이 있는 암호이지만 bac는 그렇지 않다.
새 보안 시스템에서 조교들이 암호로 사용했을 법한 문자의 종류는 C가지가 있다고 한다. 이 알파벳을 입수한 민식, 영식 형제는 조교들의 방에 침투하기 위해 암호를 추측해 보려고 한다. C개의 문자들이 모두 주어졌을 때, 가능성 있는 암호들을 모두 구하는 프로그램을 작성하시오.
입력
첫째 줄에 두 정수 L, C가 주어진다. (3 ≤ L ≤ C ≤ 15) 다음 줄에는 C개의 문자들이 공백으로 구분되어 주어진다. 주어지는 문자들은 알파벳 소문자이며, 중복되는 것은 없다.
출력
각 줄에 하나씩, 사전식으로 가능성 있는 암호를 모두 출력한다.
풀이
- 백트래킹
#include <iostream>
#include <algorithm>
using namespace std;
int L, C;
char input[15], output[15];
bool isVowel(char c) {
    return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
void backTracking(int cur, int len, int vowelCnt) {
    if(len == L) {
        if(vowelCnt < 1 || len-vowelCnt < 2) return;
        for(int i=0; i<L; i++) cout << output[i];
        cout << '\n';
        return;
    }
    for(int i=cur; i<C; i++) {
        output[len] = input[i];
        backTracking(i+1, len+1, vowelCnt + isVowel(input[i]));
    }
}
int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    cin >> L >> C;
    for(int i=0; i<C; i++) cin >> input[i];
    sort(input, input+C);
    backTracking(0, 0, 0);
}백트래킹으로 조합을 만들고 L자리 만큼 완성됐을 때 조건에 맞는지 확인하고 출력
조건이 더 많거나 포함되어야하는 모음 혹은 자음의 수가 더 많을 경우 `if(len == L)` 전에 조건을 확인하고 가지치기를 하면 경우의 수를 많이 줄일 수 있다. 또 재귀문이 들어있는 for문에서 한계값을 남은 후보의 수로 정해 가지치기가 가능하다.
for(int i=cur; i <= C-L+len; i++) {
    output[len] = input[i];
    backTracking(i+1, len+1, vowelCnt + isVowel(input[i]));
}
- next_permutation 1
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int L, C;
char input[15];
bool isVowel(char c) {
    return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    cin >> L >> C;
    for(int i=0; i<C; i++) cin >> input[i];
    sort(input, input+C);
    vector<int> mask(C);
    for(int i=L; i<C; i++) mask[i] = 1;
    do {
        string ans;
        int vowelCnt = 0;
        for(int i=0; i<C; i++) {
            if(!mask[i]) {
                if(isVowel(input[i])) vowelCnt++;
                ans += input[i];
            }
        }
        if(vowelCnt < 1 || L-vowelCnt < 2) continue;
        cout << ans << '\n';
    } while(next_permutation(mask.begin(), mask.end()));
}위 백트래킹과 같은 원리로 next_permutation을 이용해 다시 풀어봤다.
- next_permutation 2
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
char vowels[5], consonants[14];
int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int L, C; cin >> L >> C;
    int vLen = 0, cLen = 0;
    for(int i=0; i<C; i++) {
        char c; cin >> c;
        if(c == 'a'|| c == 'e'|| c == 'i'|| c == 'o'|| c == 'u') 
            vowels[vLen++] = c;
        else consonants[cLen++] = c;
    }
    sort(vowels, vowels+vLen);
    sort(consonants, consonants+cLen);
    vector<string> ans;
    for(int vCnt = max(1, L-cLen); vCnt <= min(vLen, L-2); vCnt++) {
        int cCnt = L - vCnt;
        int vMask[vLen], cMask[cLen];
        for(int i=0; i<vLen; i++) vMask[i] = i < vCnt ? 0 : 1;
        for(int i=0; i<cLen; i++) cMask[i] = i < cCnt ? 0 : 1;
        do {
            do {
                string s;
                for(int i=0; i<vLen; i++)
                    if(!vMask[i]) s.push_back(vowels[i]);
                for(int i=0; i<cLen; i++) 
                    if(!cMask[i]) s.push_back(consonants[i]);
                sort(s.begin(), s.end());
                ans.push_back(s);
            } while(next_permutation(cMask, cMask + cLen));
        } while(next_permutation(vMask, vMask + vLen));
    }
    sort(ans.begin(), ans.end());
    for(string s:ans) cout << s << '\n';
}사실 이런 유형의 문제는 고등 수학 순열과 조합에서 자주 등장하는 문제 유형이다. 자음과 모음을 따로 조합을 구해 소팅해도 된다.
- 모음에서 `vCnt` (`max(1, L - cLen) ≤ vCnt ≤ min(vLen, L-2)`)개를 뽑는다.
- 자음에서 `cCnt`(`cCnt = L - vCnt`)개를 뽑는다.
- 뽑은 문자들을 정렬한다. (`sort s`)
- 가능한 모든 문자열들을 정렬한다.(`sort ans`)
'Problem Solving > BOJ' 카테고리의 다른 글
| [백준 - 15683] 감시 - C++ (0) | 2023.11.02 | 
|---|---|
| [백준 - 1005] ACM Craft - C++ (0) | 2023.11.01 | 
| [백준 - 6603] 로또 - C++ (0) | 2023.10.31 | 
| [백준 - 14956] Philosopher’s Walk - C++ (0) | 2023.10.30 | 
| [백준 - 2448] 별 찍기 - 11 - C++ (0) | 2023.10.29 | 
