알고리즘/백준 풀이(동적 프로그래밍)

백준 1003번 - 피보나치 함수

공부 기록장 2024. 1. 2. 22:56

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

 

1003번: 피보나치 함수

각 테스트 케이스마다 0이 출력되는 횟수와 1이 출력되는 횟수를 공백으로 구분해서 출력한다.

www.acmicpc.net

 

 

다음 피보나치 문제는 풀이는 되지만 시간초과 때문에 애를 많이 먹었던 것 같다.

그리하여 Scanner 대신 BufferedReader 와 BufferedWriter를 사용하였다.(시간 면에서 다음과 같은 차이를 보인다.)

입력 방식 수행시간(초)
java.util.Scanner 6.068
java.io.BufferedReader 0.934

 

count_0은 0의 갯수,

count_1은 1의 갯수를 나타낸다.

 

 

 

코드

import java.io.*;
import java.util.*;

public class Main{
	public static void main(String[] args) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		
		
		int num = Integer.parseInt(br.readLine());
		int count_0[] = new int[41];
		int count_1[] = new int[41];
		count_0[0]=1;
		count_1[0]=0;
		count_0[1]=0;
		count_1[1]=1;
		
		for(int i=0;i<num;i++)
		{
			int n1 = Integer.parseInt(br.readLine());
			for(int j=2;j<=n1;j++)
			{
				count_0[j]=count_0[j-1]+count_0[j-2];
				count_1[j]=count_1[j-1]+count_1[j-2];
			    
			}
			bw.write(count_0[n1]+" "+count_1[n1]+"\n");
			bw.flush();
		}
		bw.close();
		br.close();
	}
}