
01. ๐ ๋ฌธ์ ํ์
n: ํผ๋ณด๋์น ์์ ์์
n=0, ํผ๋ณด๋์น ์ = 0
n=1, ํผ๋ณด๋์น ์ = 1
n์ ์ต๋๋ 1e18๋ก long long ์ฌ์ฉ
ํผ๋ณด๋์น ์๋ฅผ 1e9+7๋ก ๋ชจ๋๋ฌ ์ฐ์ฐํ์ฌ ์ถ๋ ฅ
01-1. ๊ฐ๋ฅํ ์๊ฐ ๋ณต์ก๋
๊ฐ ํผ๋ณด๋์น ์์ ๋ํด ์ ํํ์ ์, O(N)์ ์๊ฐ ๋ณต์ก๋๋ฅผ ๊ฐ์ง๋๋ผ๋ TLE ๋ฐ์
๋ฐ๋ผ์, ์๊ฐ ๋ณต์ก๋ O(log N) ์ดํ๋ก ๊ตฌํ
01-2. ์๊ณ ๋ฆฌ์ฆ ์ ํ
์ ์ดํ๋ ฌ์ ์ด์ฉํ, ๋ถํ ์ ๋ณต์ผ๋ก ๊ตฌํ
02. ๐ ์ฝ๋ ์ค๊ณํ๊ธฐ
ํผ๋ณด๋์น ์์ด์ ์ ํ์์ ๋ํ๋ด๋ฉด ์๋์ ๊ฐ์

์ ํ์์ ํ๋ ฌ๋ก ๋ณํํ๋ฉด ์๋์ ๊ฐ์ด ๋ณํํ ์ ์์



V(n)๊ณผ A๋ฅผ ์ผ์ชฝ๊ณผ ๊ฐ์ด ์ ์ํ๋ฉด,
์์ ํ๋ ฌ ์์ ์๋์ ๊ฐ์ด ๋ณํํ ์ ์์
V(n) = A^1 * V(n-1)
= A^(n-1) * V(1)
์์ ์์ ํ์ด์ฐ๋ฉด,

๋ฐ๋ผ์, (A^n-1)์ 0๋ฒ์งธ๊ฐ n๋ฒ์งธ ํผ๋ณด๋์น ์, 1๋ฒ์งธ๊ฐ n-1๋ฒ์งธ ํผ๋ณด๋์น ์๋ฅผ ๋ํ๋ธ๋ค๋ ๊ฒ์ ์ ์ ์์
์์ ๊ณผ์ ์ ์ฝ๋๋ก ๋ํ๋ด๋ฉด ์๋์ ์์๋ฅผ ๋ฐ๋ฅผ ์ ์์
- n์ ์ ๋ ฅ
- ํ๋ ฌ A์ ๋ํด์ ์ ์
- A^n์ ๊ตฌํจ
- A^(n/2) * A^(n/2) ์ ๊ตฌํ๋ ๊ณผ์ ์ ์ฌ๊ท์ ์ผ๋ก ๊ตฌํ, O(log n)์ ๋ฐ๋ฅผ ์ ์๋๋ก ํจ
- A^n์ ๊ฒฐ๊ณผ์ 0๋ฒ์งธ ์๋ n+1์ ํผ๋ณด๋์น ์๋ฅผ ๊ฐ๋ฆฌํค๊ณ , 1๋ฒ์งธ ์๋ n๋ฒ์งธ ํผ๋ณด๋์น ์๋ฅผ ๊ฐ๋ฆฌํด
03. ๐ ๏ธ ์๋๋ณ ์์
1ํ์ฐจ
- ์ง์๋ฅผ n-1๋ก ๊ณ์ฐํ์ฌ, n=1 ์ผ ๊ฒฝ์ฐ์ ์ ๋๋ก ๋ ์ถ๋ ฅ์ ํ์ง ๋ชป ํจ
2ํ์ฐจ
04. ๐๏ธ ์ ๋ต ์ฝ๋
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<vector<ll>> matrix;
const ll MOD = 1e9 + 7;
matrix operator*(const matrix& a, const matrix& b){
int N = a.size(), M = b.size(), K = b[0].size();
matrix res = matrix(N, vector<ll>(K));
for(int i = 0; i < N; i++)
for(int j = 0; j < K; j++)
for(int l = 0; l < M; l++)
res[i][j] = (res[i][j] + a[i][l] * b[l][j]) % MOD;
return res;
}
matrix pow(matrix a, ll n){
if(n == 1) return a;
const matrix half = pow(a, n / 2);
matrix res = half * half;
if(n % 2 == 1) res = res * a;
return res;
}
int main(){
cin.tie(0)->sync_with_stdio(0);
matrix A = {
{1, 1},
{1, 0}
};
ll n;
cin >> n;
matrix res = pow(A, n);
cout << res[0][1] << "\n";
return 0;
}
'Problem Solving > Baekjoon Online Judge (BOJ)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [C++] BOJ 19238 - ์คํํธ ํ์ (0) | 2025.04.21 |
|---|---|
| [C++] BOJ 12850 - ๋ณธ๋ ์ฐ์ฑ 2 (0) | 2025.04.20 |
| [C++] BOJ 2638 - ์น์ฆ (0) | 2025.04.20 |
| [C++] BOJ 9019 - DSLR (0) | 2025.04.19 |
| [C++] BOJ 23289 - ์จํ๊ธฐ ์๋ ! (0) | 2025.04.18 |
์๋ชป๋ ์ ๋ณด๊ฐ ์๋ค๋ฉด ๋ง์ํด์ฃผ์ธ์!