1. 程式人生 > >Cubes(DFS+剪枝)

Cubes(DFS+剪枝)

題意:給一個數N,求N最少由多少個數的立方構成,並輸出這些數。

做法:DFS + 剪枝,剪枝的邊界很很很重要!

#include <stdio.h>
int cub[400];
int ans[300];
int tp[300];
int n;
int sum = 0x3f3f3f3f; //個數
void dfs(int left, int depth, int pos) {
    if(left == 0 && depth < sum) {  //成立則更新ans陣列
        sum = depth;
        for(int i = 0; i < depth; i++) ans[i] = tp[i];
        return;
    }
    if(depth +1 >= sum) return;  //等於號是多麼的重要orz....
    for(int i = pos; i >= 1; i--) {
        if(cub[i] > left) continue;
        if(depth + left / cub[i] >= sum) return;  //等於號是多麼的重要orz....
        tp[depth] = i;
        dfs(left - cub[i], depth+1, i); //下一次從第i個數開始搜
    }
}
int main() {
    for(int i = 0; i < 400; i++) cub[i] = i * i * i; 
    scanf("%d", &n);
    dfs(n, 0, 366);
    printf("%d\n", sum);
    for(int i = 0; i < sum; i++) {
        if(i > 0) putchar(' ');
        printf("%d", ans[i]);
    }
    putchar('\n');
}