728x90
반응형
https://www.acmicpc.net/problem/1904
1904번: 01타일
지원이에게 2진 수열을 가르쳐 주기 위해, 지원이 아버지는 그에게 타일들을 선물해주셨다. 그리고 이 각각의 타일들은 0 또는 1이 쓰여 있는 낱장의 타일들이다. 어느 날 짓궂은 동주가 지원이
www.acmicpc.net
풀이
이 문제는 규칙을 적어보면 피보나치 수열과 같다. f(n)=f(n-1)+f(n-2)
아래의 코드는 메모이제이션을 이용한 Top-down방식을 이용하여 작성했다. 다음의 코드로 작성했을 때 시간 초과가 발생하였다.
-시간 초과 코드
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
32
33
34
35
|
using System;
using System.Text;
using System.IO;
class Program
{
static int[] cnt;
static int func(int n)
{
if (n == 1)
{
cnt[1] = 1;
return 1;
}
if (n == 2)
{
cnt[2] = 2;
return 2;
}
cnt[n] = (func(n - 1) + func(n - 2))%15746;
return cnt[n];
}
static void Main()
{
StreamReader sr = new StreamReader(new BufferedStream(Console.OpenStandardInput()));
StreamWriter sw = new StreamWriter(new BufferedStream(Console.OpenStandardOutput()));
StringBuilder sb = new StringBuilder();
cnt = new int[1000001];
int n = int.Parse(sr.ReadLine());
func(n);
sw.WriteLine(cnt[n]);
sr.Close();
sw.Close();
}
}
|
cs |
위의 방식으로 코드를 작성했을 때 시간초과가 발생하여 메모이제이션으로 이전 계산식을 저장하며 Bottom-up방식으로 코드를 작성하였더니 해결할 수 있었다.
처음 제출했을 때 코드가 틀렸다고 해서 엄청 고민하다가 문제를 잘못읽어 출력란에만 %15746을 해주었다;;;
-정답 코드
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
|
using System;
using System.Text;
using System.IO;
class Program
{
static int[] cnt;
static int func(int n)
{
cnt[0] = 1;
cnt[1] = 1;
for (int i = 2; i <= n; i++)
{
cnt[i] = (cnt[i - 1] + cnt[i - 2])%15746;
}
return cnt[n];
}
static void Main()
{
StreamReader sr = new StreamReader(new BufferedStream(Console.OpenStandardInput()));
StreamWriter sw = new StreamWriter(new BufferedStream(Console.OpenStandardOutput()));
StringBuilder sb = new StringBuilder();
cnt = new int[1000001];
int n = int.Parse(sr.ReadLine());
func(n);
sw.WriteLine(cnt[n]);
sr.Close();
sw.Close();
}
}
|
cs |
728x90
반응형
'C# > 백준 알고리즘' 카테고리의 다른 글
2022.02.06 [백준] C# RGB거리 (0) | 2022.02.06 |
---|---|
2022.02.06 [백준] C# 파도반 수열 (0) | 2022.02.06 |
2022.02.06 [백준] C# 신나는 함수 실행 (0) | 2022.02.06 |
2022.02.06 [백준] C# 피보나치 함수 (0) | 2022.02.06 |
2022.02.05 [백준] C# 좌표 압축 (0) | 2022.02.05 |
댓글