BaekJoon 2794 피보나치



피보나치 수를 구하는 방법입니다 !!

https://www.acmicpc.net/problem/1874

하지만 방법이 좀 독특합니다. 왜냐하면  점화식 두개를 이용해서 행렬을 만들고

행렬의 곱으로 한번에 계산하는 방식이죠.

MOD연산을 언제할지 헷갈렸지만 무사히 통과했습니다.




 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
import java.io.*;
import java.util.HashMap;

public class B2749 {
    final static int MOD = 1000000;
    static long N;
    static HashMap<Long, long[][]> matrices = new HashMap<>();
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        N = Long.parseLong(br.readLine());
        int ans = (N == 0) ? 0 : 1;
        long[][] zeroMatrix = {{0, 0},{0 , 0}};
        long[][] initMatrix = {{1, 1},{1 , 0}};
        matrices.put((long)0, zeroMatrix);matrices.put((long)1, initMatrix);
        if (N > 2) {
            long[][] mat = getMatrix(N - 2);
            ans = (int) (mat[0][0] + mat[0][1]) % MOD;
        }
        bw.write(ans + "\n");bw.flush();bw.close();

    }
    public static long[][] getMatrix(long n) {
        if (n == 1) return matrices.get((long)1);
        else if (matrices.containsKey(n)) return matrices.get(n);
        else {
            matrices.put(n, (n % 2 == 0) ? multiplication(getMatrix(n / 2), getMatrix(n / 2)) :
                    multiplication(getMatrix(n / 2), multiplication(getMatrix(n / 2), getMatrix(1))));
            return matrices.get(n);
        }
    }
    public static long[][] multiplication(long[][] a, long[][] b) {
        long[][] ans = new long[2][2];
        ans[0][0] = (a[0][0] * b[0][0] + a[0][1] * b[1][0]) % MOD;
        ans[0][1] = (a[0][0] * b[0][1] + a[0][1] * b[1][1]) % MOD;
        ans[1][0] = (a[1][0] * b[0][0] + a[1][1] * b[1][0]) % MOD;
        ans[1][1] = (a[1][0] * b[0][1] + a[1][1] * b[1][1]) % MOD;
        return ans;
    }
}

이 블로그의 인기 게시물

웹툰 무료로 볼 수 있는 사이트

BackJoon 1011, Fly me to the alpha centauri, 규칙 찾기 문제

BaekJoon 14503, 로봇 청소기