본문 바로가기
알고리즘/백준 BOJ

[ BOJ/C# ] 1003 피보나치 함수

by 왹져박사 2023. 9. 21.
728x90

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

 

1003번: 피보나치 함수

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

www.acmicpc.net

시간제한이 0.25초이기 때문에, 피보나치수열을 저장해 가며 업데이트 해가는 방법으로 풀었다. 

미리 만들어둔 배열에 최댓값 이상일 경우, 최대값+1부터 n까지의 배열을 업데이트한다. 

using System;
using System.Text;

namespace B1003
{
    class Program
    {

        static void Main()
        {
            StreamReader sr = new StreamReader(Console.OpenStandardInput());
            StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
            StringBuilder sb = new StringBuilder();

            int t = int.Parse(sr.ReadLine());
            int[,] ints = new int[41, 2];
            ints[0, 0] = 1;
            ints[0, 1] = 0;
            ints[1, 0] = 0;
            ints[1, 1] = 1;
            int max = 1;
            for(int i = 0; i < t; i++)
            {
                int n = int.Parse(sr.ReadLine());
                if(n > max)
                {
                    for (int j = max + 1; j <= n; j++)
                    {
                        ints[j, 0] = ints[j - 1, 0] + ints[j - 2, 0];
                        ints[j, 1] = ints[j - 1, 1] + ints[j - 2, 1];
                    }
                    sb.Append(ints[n, 0] + " " + ints[n, 1] + "\n");
                    max = n;
                }
                else sb.Append(ints[n, 0] + " " + ints[n, 1] + "\n");
            }
            sw.Write(sb);
            sr.Close();
            sw.Flush();
            sw.Close();
        }
    }
}

처음에는 n을 넣으면 모든 값을 구하는 방식으로 했지만 시간초과였고, 

두번째는 max값에 +1을 해주지 않아 틀렸다. 

728x90

'알고리즘 > 백준 BOJ' 카테고리의 다른 글

[ BOJ/C# ] 11727 2×n 타일링 2  (0) 2023.09.23
[ BOJ/C# ] 11726 2×n 타일링  (0) 2023.09.22
[ BOJ/C# ] 9095 1, 2, 3 더하기  (0) 2023.09.19
[ BOJ/C# ] 1463 1로 만들기  (0) 2023.09.18
[ BOJ/C# ] 11723 집합  (0) 2023.09.18