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); } }
  • 相关阅读:
    Excel中substitute替换函数的使用方法
    如何在Excel中提取小数点后面的数字?
    提升单元测试体验的利器--Mockito使用总结
    SpringMVC项目读取不到外部CSS文件的解决办法及总结
    java8 Lambda表达式的新手上车指南(1)--基础语法和函数式接口
    Spring-data-redis操作redis知识总结
    优雅高效的MyBatis-Plus工具快速入门使用
    Thrift入门初探(2)--thrift基础知识详解
    Thrift入门初探--thrift安装及java入门实例
    spring事件驱动模型--观察者模式在spring中的应用
  • 原文地址:https://www.cnblogs.com/liyinggang/p/5742262.html
Copyright © 2011-2022 走看看