티스토리 뷰
728x90
문제 링크
https://www.acmicpc.net/problem/1003기본적인 피보나치 문제를 모르거나 시간초과가 문제라면
http://degurii.tistory.com/14?category=755814
를 참고하자.
기존의 피보나치 함수가
f(n)=f(n−2)+f(n−1)
이므로
n일때 호출되는 0과 1의 개수를 [0의개수, 1의개수]n 로 표현해서 단순히
[i,j]n=[i,j]n−2+[i,j]n−1 처럼 쓸 수 있다.
이때, [i,j]+[x,y]=[i+x,j+y]로 정의한다.
정답 코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
using pii = pair<int, int>; | |
int n, t; | |
pii d[50]; | |
pii operator + (const pii &a, const pii &b) { | |
return { a.first + b.first, a.second + b.second }; | |
} | |
int main() { | |
ios_base::sync_with_stdio(false); | |
cin.tie(0); | |
d[0] = { 1, 0 }; | |
d[1] = { 0, 1 }; | |
for (int i = 2; i <= 40; i++) { | |
d[i] = d[i - 1] + d[i - 2]; | |
} | |
cin >> t; | |
while (t--) { | |
cin >> n; | |
cout << d[n].first << ' ' << d[n].second << '\n'; | |
} | |
} |
728x90
'알고리즘 > 문제 풀이' 카테고리의 다른 글
[BOJ] 백준 1005 ACM Craft (0) | 2018.06.28 |
---|---|
[BOJ] 백준 1004 어린 왕자 (0) | 2018.06.28 |
[BOJ] 백준 2747 피보나치 수 (0) | 2018.06.28 |
[BOJ] 백준 1002 터렛 (0) | 2018.06.27 |
[BOJ] 백준 1001 A - B (0) | 2018.06.27 |