본문 바로가기
#DevStudy/문제풀이

[Baekjoon] 1149 - RGB

by 검은_백조 2016. 10. 11.


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




[재귀함수 활용]

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdio.h>
#include <stdlib.h>
 
int houseCount;
int houseColor[1000][3];
 
int min(int a, int b)
{
    return a > b ? b : a;
}
 
int GetPaintCost(int n, int color)
{
    if(n == houseCount)
        return 0;
    
    
    // 다음 위치 색상을 정해야 한다.
    // 내 색이 아닌 것 중에 고른다.
    int cost = 0;
 
    if(color == 0) cost = min(GetPaintCost(n + 11), GetPaintCost(n + 12));
    if(color == 1) cost = min(GetPaintCost(n + 10), GetPaintCost(n + 12));
    if(color == 2) cost = min(GetPaintCost(n + 10), GetPaintCost(n + 11));
    
    
    
    return cost + houseColor[n][color];
}
 
 
int main() {
    scanf("%d\n"&houseCount);
    
    for(int i = 0; i < houseCount; i++){
        scanf("%d"&houseColor[i][0]);
        scanf("%d"&houseColor[i][1]);
        scanf("%d"&houseColor[i][2]);
    }
    
    // 처음 위치에 정한 색상 r,g,b 중 최소값
    int cost = min(min(GetPaintCost(00), GetPaintCost(01)), GetPaintCost(02));
    
    printf("%d\n", cost);
    
    
    return 1;
}
cs




[동적 계획법 활용]

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
#include <stdio.h>
#include <stdlib.h>
 
int houseCount;
int Cost[1000];
 
int min(int a, int b)
{
    return a > b ? b : a;
}
 
int main() {
    int r = 0, g = 0, b = 0;
    int prevR = 0, prevG = 0, prevB = 0;
    scanf("%d\n"&houseCount);
    
    for(int i = 0; i < houseCount; i++){
        prevR = r;
        prevG = g;
        prevB = b;
        
        scanf("%d"&r);
        scanf("%d"&g);
        scanf("%d"&b);
        
        r = min(prevG, prevB) + r;
        g = min(prevR, prevB) + g;
        b = min(prevR, prevG) + b;
    }
    int result = min(min(r, g), b);
    printf("%d", result);
    
    
    return 1;
}
cs



i 의 비용 =  (i - 1) 의 비용 + i 에 칠할 색의 비용


i 에 칠할 r, g, b 에 대하여 각각 (i - 1) 의 색과 겹치지 않도록

r = (i - 1)의 g, b 중 작은 것,

g = (i - 1)의 r, b 중 작은 것

b = (i - 1)의 r, g 중 작은 것    ... 식으로 계산


'#DevStudy > 문제풀이' 카테고리의 다른 글

[Baekjoon] 1932 - 숫자삼각형  (0) 2016.10.12
[Baekjoon] 2579 - 계단오르기  (0) 2016.10.11
[P.C] 3. 여행 (The trip)  (0) 2016.09.23
[P.C] 2. 지뢰찾기 (Minesweeper)  (0) 2016.09.23
[Baekjoon] 5393 콜라츠  (0) 2016.09.22

댓글