-
반응형
https://www.acmicpc.net/problem/4779
4779번: 칸토어 집합
칸토어 집합은 0과 1사이의 실수로 이루어진 집합으로, 구간 [0, 1]에서 시작해서 각 구간을 3등분하여 가운데 구간을 반복적으로 제외하는 방식으로 만든다. 전체 집합이 유한이라고 가정하고,
www.acmicpc.net
풀이
전체문제를 부분적으로 쪼개어 문제를 해결하는 분할정복에 해당하는 문제이다.
1. 입력받은 N값으로 초기 문자열을 만들어 준다.
2. 재귀함수를 이용하여 분할정복을 시작한다.
2-0. 베이스케이스 = 해당 토막의 길이가 1
2-1. 3등분을 한다.
2-2. 첫번째 토막은 재귀함수를 호출한다.
2-3. 두번째 토막은 모두 공백으로 바꾸어준다.
2-4. 세번째 토막은 재귀함수를 호출한다.
코드
#include<iostream> #include<algorithm> #include<cmath> #include<string> using namespace std; string init(int n) { string str = ""; for (int i = 0; i < n; i++) str += "-"; return str; } void make_blank(string& str, int st, int end) { for (int i = st; i <= end; i++) { str[i] = ' '; } } void func(string& str,int st,int end) { if (st==end) { return; } int size = (end-st+1) / 3; func(str, st, st+size - 1); make_blank(str, st+size,end-size); func(str, end - size + 1, end); } int main() { int n; while (cin >> n) { n = pow(3, n); string str = init(n); func(str, 0, n - 1); cout << str << "\n"; } return 0; }
반응형'문제풀이 > 백준oj' 카테고리의 다른 글
[백준OJ] 10282번 해킹 (0) 2021.09.26 [백준OJ] 2933번 미네랄 (0) 2021.09.26 [백준OJ] 6416번 트리인가? (0) 2021.09.25 [백준OJ] 1520번 내리막 길 (0) 2021.09.16 [백준OJ] 5547번 일루미네이션 (0) 2021.09.15 댓글