목록분할정복 (8)
Dev.baelanche
입력된 수가 홀수 일때 정삼각형, 짝수 일때 역삼각형을 그리는 규칙을 가졌다. 삼각형은 외곽선만 존재하고 n 입력시 n-1, n-2, ... , (n>0일때까지) 를 재귀하며 내부에 삼각형을 그려야 한다. 문제 예제 출력 부분을 드래그 해보면 알 수 있을텐데 * 우측의 빈공간에는 공백이 없다. k*k 형식으로 우측을 공백으로 채우면 출력형식 오류를 반환하니 우측의 공백은 없애주어야 한다. 코드 클린 작업을 하지 않아서 지저분하지만 삼각형을 그리는 부분은 대충 확인 가능할 것이다. public class Main { static char a[][]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc..
분할정복으로 * * * ***** 모양을 위, 왼쪽, 오른쪽으로 3등분하여 재귀호출하여 구현했다. public class Main { static char a[][]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int alpha = n/3 - 1; a = new char[n][n/3*5 + alpha]; for(int i=0; i
n 이 커질수록 네모의 개수가 비례하여 증가한다. n 일때 출력될 가로, 세로 길이를 유추하고 분할정복으로 구현했다. public class Main { static char a[][]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int len = 1; for(int i=1; i
어느 부분이 반복되는지 한 3분정도 보다가 찾아냈다. *** * * *** 모양을 재귀호출하면서 채워넣어주면 된다. 예제를 생각해보면, 1. 27*27 배열을 9*9 씩 9개로 분할한다. 2. 9개 배열 중 가운데 배열만 공백으로 채우고 나머지는 *로 채운다. 3. 9개 배열을 3*3 씩 9개로 분할한다. 4. 2번과 같이 채운다. 5. 3*3 의 배열을 채우면 정지한다. 위 순서대로 3^n * 3^n 의 배열에서 3등분 하는 방법으로 접근하면 된다. public class Main { static char a[][]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); a = ..
2^n * 2^n 의 배열에서 좌상, 우상, 좌하, 우하 순으로 분할하여 접근한다. 재귀를 이용하여 접근한 부분배열의 크기가 2*2 일때까지 접근하여 카운트를 세고 (r, c) 일때의 카운트를 출력해주면 된다. public class Main { static int idx = 0; static int r; static int c; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int pow = (int)Math.pow(2, n); r = sc.nextInt(); c = sc.nextInt(); recursive(0, 0, pow); } public static void re..
1780번 문제와 동일한 방식으로 풀면된다. 다만 재귀가 깊어질수록 출력할 숫자 좌우에 괄호를 붙여주어야 하는데, 필자는 큐에 담아서 pop 하는 방식으로 구현했다. public class Main { static char[][] a; static Queue q = new LinkedList(); public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); a = new char[n][n]; for(int i=0; i
분할정복을 사용하는 전형적인 문제이다. 종이의 크기를 9로 예를 들면 1. 9*9 를 탐색한다. 2. 종이가 모두 같은 수로 되어있지 않다면 9등분하여 각 종이를 탐색한다. 3. 2번을 반복하여 -1, 0, 1 의 개수를 센다. 2번이 계속 반복되므로 재귀함수로 짜주기만 하면 된다. 코드를 보고 머리로 그려보는 것이 좋을 것 같다. public class Main { static int a[][]; static int cnt[] = new int[3]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); a = new int[n][n]; for(int i=0; i
x제곱 하기에 수가 너무 크므로 분할하는 방법으로 접근해야 한다. B를 2로 계속 나누어 최대한 작은 수로 만들고 매 연산마다 (A*B)%C = ((A%C)*(B%C))%C 를 이용하여 수를 더 작게 만들어준다. public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); long ans = 1; long mul = a % c; while(b>0) { if(b%2 == 1) { ans *= mul; ans %= c; } mul = ((mul % c) * (mul % c)) %..