문제 출처: https://www.acmicpc.net/problem/1759
두 가지 방법으로 풀어보았습니다.
첫번 째 풀이는 배열에 담은 요소가 L개가 됐을 때 배열에서 자음과 모음을 매번 확인하는데, 입력범위가 커질 때 비효율적일 것같습니다.
두 번째 풀이는 string을 이용해서 풀었습니다.
풀이1
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 42 43 | #include<iostream> #include<algorithm> using namespace std; int l, c; char arr[16], code[16]; void dfs(int start, int cnt); int main() { cin >> l >> c; for (int i = 0; i < c; i++) cin >> arr[i]; sort(arr, arr + c); dfs(0,0); } void dfs(int start, int cnt) { if (cnt == l) { int index1 = 0; int index2 = 0; for (int i = 0; i < l; i++) { if (code[i] == 'a' || code[i] == 'e' || code[i]=='i'||code[i] == 'o' || code[i] == 'u') index1++; else index2++; } for (int i = 0; i < l; i++) { if (index1 >= 1 && index2 >= 2) cout << code[i]; else return; } cout << endl; return; } for (int i = start; i < c; i++) { code[cnt] = arr[i]; dfs(i + 1, cnt + 1); } } | cs |
풀이2
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 | #include<iostream> #include<algorithm> #include<string> using namespace std; int l, c; char arr[16], code[16]; void dfs(int start, int mo,int ja,string s); int main() { cin.tie(0); cin >> l >> c; for (int i = 0; i < c; i++) cin >> arr[i]; sort(arr, arr + c); dfs(0,0,0,""); } void dfs(int start, int mo, int ja, string s) { if (s.size() == l) { if (mo >= 1 && ja >= 2) cout << s << '\n'; return; } for (int i = start; i < c; i++) { if (arr[i] == 'a' || arr[i] == 'e' || arr[i] == 'i' || arr[i] == 'o' || arr[i] == 'u') dfs(i + 1, mo + 1, ja,s+arr[i]); else dfs(i + 1, mo, ja + 1, s + arr[i]); } } | cs |
결과
'문제풀이(BOJ) > DFS,BFS' 카테고리의 다른 글
[백준 2206] 벽 부수고 이동하기 (0) | 2020.02.11 |
---|---|
[백준 17836] 공주님을 구해라! (0) | 2020.02.10 |
[백준] 촌수계산 (0) | 2020.01.20 |
[백준 2589] 보물섬(BFS) (0) | 2020.01.17 |
[백준 14502] 연구소 (BFS) (0) | 2020.01.17 |