곽로그

[백준 9461, Java] 파도반 수열 본문

알고리즘/백준

[백준 9461, Java] 파도반 수열

일도이동 2020. 11. 27. 00:34
반응형

문제

www.acmicpc.net/problem/9461

 

9461번: 파도반 수열

오른쪽 그림과 같이 삼각형이 나선 모양으로 놓여져 있다. 첫 삼각형은 정삼각형으로 변의 길이는 1이다. 그 다음에는 다음과 같은 과정으로 정삼각형을 계속 추가한다. 나선에서 가장 긴 변의

www.acmicpc.net

 

풀이

 - 그림을 볼 필요 없이 수열을 보면 점화식을 구할 수 있다. f(n) = f(n-2) + f(n-3) (단 n=1,2,3일 때는 1)

- 구한 점화식을 가지고서 topDown방식, bottomUp 방식으로 풀 수 있다.

- 이때 주의해야할 점은 문제에서 주어지는 n은 "n번째"의 개념이기 때문에 메모이제이션의 배열 index와 구분해야한다. 

- 그리고 답의 범위는 long

 

코드

 

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Main {
    public static int T;
    public static int N;
    public static long[] numArray;
    public static long[] memo;
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        T = Integer.parseInt(br.readLine());
        N=101;
        numArray = new long[N];
        memo = new long[N];

        for(int t = 0; t<T; t++){
            int n = Integer.parseInt(br.readLine());
            long result = bottomUp(n);
            bw.write(String.valueOf(result)+"\n");
        }

        bw.flush();

    }

    public static long topDown(int n){
        if(n<3){
            memo[n] =1;
            return 1;
        }
        else if(memo[n]!=0){
            return memo[n];
        }
        else{
            memo[n] = topDown(n-2) + topDown(n-3);
            return memo[n];
        }
    }

    public static long bottomUp(int n){
        if(memo[n] !=0){
            return memo[n];
        }

        for(int index = 1; index<=n; index++){
            if(index<=3){
                memo[index] = 1;
            }
            else{
                memo[index] = memo[index-2] + memo[index-3];
            }
        }
        return memo[n];
    }
}
반응형

'알고리즘 > 백준' 카테고리의 다른 글

[백준 1476, Java] 날짜 계산  (0) 2020.11.27
[백준 1107, Java] 리모컨  (0) 2020.11.27
[백준14500, Java] 테트로미노  (0) 2020.11.26
[백준 2800, Java] 괄호제거  (1) 2020.11.26
[백준 2309, Java] 일곱 난쟁이  (0) 2020.11.24
Comments