zoukankan      html  css  js  c++  java
  • 小木棍(暴搜)

    小木棍(暴搜)

    一个人有一堆一样长的木棍,现在他把它们随便切,切出来n个小木棍(n<65)。现在他不知道原来的木棍多长了,请你告诉他原来的木棍最短多长。

    这道题是搜索+剪枝题。各种神奇剪枝都写在代码里了。

    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <functional>
    using namespace std;
    
    const int maxn=100;
    int m, n, a[maxn], sum, ans;
    int visit[maxn], flag;
    
    //参数分别是剩下多少对,当前长度,从哪开始枚举
    //beg是必要的,不然就变成排列了
    void dfs(int now, int len, int beg){
        if (now==0){ printf("%d
    ", ans); exit(0); }
        if (ans-len<a[n]) return;
        for (int i=beg; i<=n; ++i){
            if (visit[i]||len+a[i]>ans) continue;
            if (!visit[i-1]&&a[i]==a[i-1]) continue;
            visit[i]=1;
            if (len+a[i]==ans) dfs(now-1, 0, 1);
            else dfs(now, len+a[i], i+1); //i+1打成beg+1了。。
            visit[i]=0;
            if (len+a[i]==ans||len==0) break;
            //新一组只搜最长的
            //神の优化:如果还差的长度等于目前的小木棒,
            //并且无解,肯定不用再搜了
        }
    }
    
    int main(){
        scanf("%d", &m); int t;
        for (int i=1; i<=m; ++i){
            scanf("%d", &t);
            if (t>50) continue;
            sum+=(a[++n]=t);
        }
        sort(a+1, a+1+n, greater<int>());
        for (ans=a[1]; ans<=sum/2; ++ans){
            if (sum%ans) continue;
            dfs(sum/ans, 0, 1);
        }
        printf("%d
    ", sum);
        return 0;
    }
    
  • 相关阅读:
    自编游戏
    宣言
    Leetcode: 12. Integer to Roman
    Leetcode: 11. Container With Most Water
    Leetcode: 10. Regular Expression Matching
    网络编程:listen函数
    网络编程:connect函数
    Leetcode: 9. Palindrome Number
    Leetcode: 8. String to Integer (atoi)
    Leetcode: 7. Reverse Integer
  • 原文地址:https://www.cnblogs.com/MyNameIsPc/p/8011506.html
Copyright © 2011-2022 走看看