티스토리 뷰

반응형


#. Problem


* The copyright in this matter is in BOJ



#. Resolution Process

  1. Read and understand problem

  2. Redefine the problem + abstract

  3. Create solution plan (select Algorithm, Data structure)

  4. Prove the plan (check performance time and usage memory)

  5. Carry out the plan

  6. Look back on the plan and find a way to improve it


#. Solve

  1. 


#. Code

Code 1) 

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
#include <iostream>
 
using namespace std;
 
int tc, N, p0, p1;
 
int fibonacci(int n) {
    if (n == 0) {
        p0++return 0;
    }
    else if (n == 1) {
        p1++return 1;
    }
    else {
        return fibonacci(n - 1+ fibonacci(n - 2);
    }
}
 
int main() {
    ios::sync_with_stdio(false);
    cin >> tc;
 
    while (tc--) {
        cin >> N;
        p0 = 0; p1 = 0;
 
        fibonacci(N);
        cout << p0 << ' ' << p1<<'\n';
    }
    return 0;
}
cs

- 기본적인 생각대로 해결했을 경우이다. 당연히 시간 초과..


Code 2) 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
 
using namespace std;
 
int tc, N;
int fb[42= {1};
 
int main() {
    ios::sync_with_stdio(false);
    cin >> tc;
 
    for (int i = 2; i < 42; i++) {
        fb[i] = fb[i - 1+ fb[i - 2];
    }
 
    while (tc--) {
        cin >> N;
        
        cout << fb[N] << ' ' << fb[N+1<< '\n';
    }
 
    return 0;
}
cs

- 이 문제도 2748번 문제를 풀었을 때 처럼 배열을 이용한다면 더 쉽고 직관적으로 풀 수 있을 것 같다.

  우선 동적 계획법으로 문제를 풀 때, 규칙을 찾아내는 것이 우선이다.

  N에 따른 0의 개수는 1, 0, 1, 1, 2, 3 ....

  N에 따르 1의 개수는 0, 1, 1,2 ,3 ,5 ... 규칙 안에 피보나치 수열이 보이게 된다. 

  

  우선, 피보나치 수열을 배열에 저장하고,

  규칙에 맞게 배열을 잘 참조하면 된다. 

  

#. Result

  - Input --------------------------------------------------------

3

0

1

3

------------------------------------------------------------------


  - Output --------------------------------------------------------

1 0

0 1

1 2

------------------------------------------------------------------



반응형

'PS > Problem_Solving' 카테고리의 다른 글

[BOJ] 17614번. 369  (0) 2020.04.19
[BOJ] 1904번. 01타일  (0) 2020.02.04
[BAEKJOON] 2748번. 피보나치 수 2  (0) 2020.02.04
[BAEKJOON] 11725번. 트리의 부모 찾기.cpp  (0) 2020.02.04
[Programmers] Network (DFS/BFS).cpp  (0) 2020.01.15
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday