zoukankan      html  css  js  c++  java
  • poj1011 Sticks (dfs剪枝)

    【题目描述】

    	George took sticks of the same length and cut them randomly until all parts became at most 50 units long. Now he wants to return sticks to the original state, but he forgot how many sticks he had originally and how long they were originally. Please help him and design a program which computes the smallest possible original length of those sticks. All lengths expressed in units are integers greater than zero.
    

    【题目链接】

    Sticks

    【算法】

    枚举答案对每一种情况构造+判定。剪枝技巧:

    
     1. 优化搜索顺序
     2. 排除等效冗余
    	 (1)构造选取的棍子递减的取
    	 (2)初始为0的棍子若无法构造出答案,则该分支减去
    	 (3)构造选取的棍子不重复选择同样长度的已经失败过的棍子。
    

    【代码】

    #include <stdio.h>
    #include <algorithm>
    #include <cstring>
    using namespace std;
    int n,all,lim;
    int a[100],v[100];
    bool dfs(int cur,int len,int last) {
        if(cur>all) return 1;
        if(len==lim) return dfs(cur+1,0,1);
        int fail=0;
        for(int i=last;i<=n;i++) {
            if(!v[i]&&len+a[i]<=lim&&a[i]!=fail) {
                v[i]=1;
                if(dfs(cur,len+a[i],i+1)) return 1;
                fail=a[i];
                v[i]=0;
                if(len==0) return 0;
            }
        }
        return 0;
    }
    int main() {
        while(~scanf("%d",&n)&&n) {
            int sum=0,val=0;
            for(int i=1;i<=n;i++) scanf("%d",&a[i]),sum+=a[i],val=max(a[i],val);
            sort(a+1,a+n+1);
            reverse(a+1,a+n+1);
            for(lim=val;lim<=sum;lim++) {
                if(sum%lim==0) {
                    all=sum/lim; memset(v,0,sizeof(v));
                    if(dfs(1,0,1)) break;
                }
            }
            printf("%d
    ",lim);
        }
        return 0;
    }
    
    
  • 相关阅读:
    (04)-Python3之--字典(dict)操作
    word2vec简单介绍
    基于websocket爬虫
    Python数据结构之链表(1)-->单链表
    词云wordcloud
    Neo4j--第一章
    AHP(层次分析法) 附Python示例代码(觉得还可以的,帮忙点个赞,谢谢)
    几种归一化方法(Normalization Method)python实现
    EM算法之Python
    通俗易懂的EM
  • 原文地址:https://www.cnblogs.com/Willendless/p/9522744.html
Copyright © 2011-2022 走看看