반응형

www.acmicpc.net/problem/1759

 

1759번: 암호 만들기

첫째 줄에 두 정수 L, C가 주어진다. (3 ≤ L ≤ C ≤ 15) 다음 줄에는 C개의 문자들이 공백으로 구분되어 주어진다. 주어지는 문자들은 알파벳 소문자이며, 중복되는 것은 없다.

www.acmicpc.net

1. n개 중 r개 뽑기

1
2
3
4
5
6
7
8
9
10
void dfs(int idx, int step) {
    if (step == l) {
        // 종료 조건
        return;
    }
    for (int i = idx; i < c; i++) {
        ans[step] = arr[i];
        dfs(i + 1, step + 1);
    }
}
cs

2. 모음 최소 1개, 자음 최소 2개

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
if (step == l) {
    int cnt1 = 0, cnt2 = 0;
    rep(i, l) {
        if (ans[i] == 'a' || ans[i] == 'e' || ans[i] == 'i' || ans[i] == 'o' || ans[i] == 'u')
            cnt1++;
        else
            cnt2++;
        // 조건 만족하면 바로 출력
        if (cnt1 >= 1 && cnt2 >= 2) {
            rep(i, l)
                cout << ans[i];
            cout << '\n';
            return;
        }
    }
    return;
}
cs

 

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
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <algorithm>
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
char arr[16];
char ans[16];
int l, c;
// 모음 최소 1개
// 자음 최소 2개
void dfs(int idx, int step) {
if (step == l) {
    int cnt1 = 0, cnt2 = 0;
    rep(i, l) {
        if (ans[i] == 'a' || ans[i] == 'e' || ans[i] == 'i' || ans[i] == 'o' || ans[i] == 'u')
            cnt1++;
        else
            cnt2++;
        // 조건 만족하면 바로 출력
        if (cnt1 >= 1 && cnt2 >= 2) {
            rep(i, l)
                cout << ans[i];
            cout << '\n';
            return;
        }
    }
    return;
}
    for (int i = idx; i < c; i++) {
        ans[step] = arr[i];
        dfs(i + 1, step + 1);
    }
}
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> l >> c;
    rep(i, c)
        cin >> arr[i];
    sort(arr, arr + c);
    dfs(00);
}
cs
반응형

'백준 > 백트래킹' 카테고리의 다른 글

백준 10819  (0) 2021.02.03
백준 1987  (0) 2021.02.03
백준 1182  (0) 2021.01.30
백준 6603  (0) 2021.01.30
백준 9663  (0) 2021.01.26

+ Recent posts