본문 바로가기

코딩테스트 준비/[백준]

[백준] 박스채우기 1493번 c++ 풀이

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

 

1493번: 박스 채우기

세준이는 length × width × height 크기의 박스를 가지고 있다. 그리고 세준이는 이 박스를 큐브를 이용해서 채우려고 한다. 큐브는 정육면체 모양이며, 한 변의 길이는 2의 제곱꼴이다. (1×1×1, 2×2×2,

www.acmicpc.net

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
#include <cstdio>
#include<cmath>
int length, width, height, n, a, b, cubes[20];
bool flag = true;
int recursive_func(int l, int w, int h){
    if((l<=0|| (w<=0|| (h<=0)){
        return 0;
    }
    int k = l;
    if(w<k){k = w;}
    if(h<k){k = h;}
    int t=log2(k);
    while(t>=0){
        int x = pow(2, t);
        if(cubes[t] > 0){
            cubes[t]--;
            return recursive_func(l-x, x, h) + recursive_func(x, x, h-x) + recursive_func(l, w-x, h) + 1;
        }
        t = t - 1;
    }
    
    flag = false;
    return -1;
}
 
int main(){
    scanf("%d %d %d"&length, &width, &height);
    scanf("%d"&n);
    for(int i=0; i<n; i++){
        scanf("%d %d"&a, &b);
        cubes[a] = b;
    }
    int answer = recursive_func(length, width, height);
    if(flag){
        
        printf("%d", answer);
    }
    else{
        printf("%d"-1);
    }
        
}
cs

 

그리디 분할정복