zoukankan      html  css  js  c++  java
  • hdu 1455(DFS+好题+经典)

    Sticks

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
    Total Submission(s): 9414    Accepted Submission(s): 2776


    Problem Description
    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.
     
    Input
    The input contains blocks of 2 lines. The first line contains the number of sticks parts after cutting, there are at most 64 sticks. The second line contains the lengths of those parts separated by the space. The last line of the file contains zero.
     
    Output
    The output file contains the smallest possible length of original sticks, one per line.
     
    Sample Input
    9 5 2 1 5 2 1 5 2 1 4 1 2 3 4 0
     
    Sample Output
    6 5
     
    题意:给多组数据,每组数据代表一些小木棍,能否将它们全部用完组成(尽量)多个相同长度的长棍,并输出长棍的长度。
    题解:有强剪枝,,多一个if(l==0) return false就AC了。。真的是NB啊,这处剪枝的作用:当len==0时,证明当前是在构造一根新的木棍,而这个第一根和其后面的所有的木棍都无法组合,那么这根木棍永远都无法用到了,所以我们直接返回上一层。下面那个while循环的剪枝作用就是当前木棍无法用到,那么其后面的所有的木棍都无法用到了,跳过即可。
    #include <cstdio>
    #include <cstring>
    #include <queue>
    #include <algorithm>
    #include <stdlib.h>
    using namespace std;
    
    int n,sum,num;
    int v[100];
    bool vis[100];
    int cmp(int a,int b){
        return a>b;
    }
    bool dfs(int len,int l,int cnt,int pos){
        if(cnt==num) return true;
        for(int i=pos;i<n;i++){
            if(vis[i]) continue;
            if(len==l+v[i]){
                vis[i] = true;
                if(dfs(len,0,cnt+1,0)) return true;
                vis[i] = false;
           return false; ///加了这个才能过poj,这个代表如果当前长度的木棍以后的木棍都拼不出这个长度了,那么就没必要试这个长度了,(后面都比当前小...)直接跳出..ORZ }
    else if(len>l+v[i]){ vis[i] = true; if(dfs(len,l+v[i],cnt,i+1)) return true; vis[i] = false; if(l==0) return false; while(v[i]==v[i+1])i++; } } return false; } int main(){ while(scanf("%d",&n)!=EOF,n){ sum = 0; for(int i=0;i<n;i++){ scanf("%d",&v[i]); sum+=v[i]; } sort(v,v+n,cmp); int ans = sum; for(int i=v[0];i<=sum;i++){ if(sum%i!=0) continue; num = sum/i; memset(vis,false,sizeof(vis)); if(dfs(i,0,0,0)) { ans = i; break; } } printf("%d ",ans); } }
  • 相关阅读:
    postgres 常见错误之字段关联不明确
    nginx proxy_pass 配置
    css font-family有哪些
    Inno Setup [Run] Section 双引号嵌套
    ubuntu16.04下ftp服务器的安装与配置
    How to check if directory exist using C++ and winAPI
    Ubuntu parted 命令 写在脚本里时要带 -s 参数
    Ubuntu syslog 太多的 named[1195]: error (network unreachable) resolving './DNSKEY/IN': 2001:7fd::1#53
    Ubuntu忘记超级用户root密码,重新设置密码 转载
    Python 替换文本中的某些词语
  • 原文地址:https://www.cnblogs.com/liyinggang/p/5742262.html
Copyright © 2011-2022 走看看