zoukankan      html  css  js  c++  java
  • Cubes(DFS+剪枝)

    题意:给一个数N,求N最少由多少个数的立方构成,并输出这些数。

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

    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
    #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 ", sum);
        for(int i = 0; i < sum; i++) {
            if(i > 0) putchar(' ');
            printf("%d", ans[i]);
        }
        putchar(' ');
    }
  • 相关阅读:
    php多态
    ssl certificate problem: self signed certificate in certificate chain
    test plugin
    open specific port on ubuntu
    junit vs testng
    jersey rest service
    toast master
    use curl to test java webservice
    update folder access
    elk
  • 原文地址:https://www.cnblogs.com/bestwzh/p/6730596.html
Copyright © 2011-2022 走看看