zoukankan      html  css  js  c++  java
  • hdu 1145(Sticks) DFS剪枝

    Sticks

    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
    #include <stdio.h>
    #include <string.h>
    #include <algorithm>
    using namespace std;
    const int N = 100; 
    int n;
    int s[N];
    int v[N];
    int t, length;  //个数  长度 
    bool cmp(int a, int b){
        return a > b;
    }
    bool dfs(int k, int len, int pos){  //第k根  第k跟长度  下标  
        
        //程序出口 
        if(k == t) return true; // 进来的时候肯定是  k = t, len = 0, pos = ? 最后一根的长度肯定是刚好等于  length  !!
        
        if(len == length) return dfs(k+1, 0, 0);  //拼接下一根 
        
        for(int i = pos+1; i <= n; i++){
            if(!v[i] && len+s[i] <= length){
                v[i] = 1;
                if(dfs(k, len+s[i], i)) return true; //这种情况可以 下面的就不用看了 
                v[i] = 0;
                
                // len+s[i] 这种情况不行  
                if(len == 0) return false;  //拼接第 k 跟木棒的 第一节的时候 不能拼成 length   return false 
                while(s[i] == s[i+1]){  //相同的就不用看了 
                    i++;
                }
            }
        } 
        return false;
    }
    int main(){
        while(~scanf("%d", &n) && n){
            int sum = 0;
            for(int i = 1; i <= n; i++){
                scanf("%d", &s[i]);
                sum += s[i];
            }
            sort(s+1, s+1+n, cmp);  //降序
            for(int i = s[1]; i <= sum; i++){
                if(sum%i == 0){
                    memset(v, 0, sizeof v);
                    length = i;  
                    t = sum / i; //组成的木棒个数
                    if(dfs(1, 0, 0)){//当前木棒数, 当前木棒数的长度, 下标 
                        printf("%d
    ", i);
                        break;
                    }
                }
            }
        }    
        return 0;
    }
  • 相关阅读:
    div弹出层
    经典SQL语句
    sql连接及操作
    给flash加上连接
    在c#中图片原比例缩放
    悬浮提示筐
    拖动板块
    IFrame自适应高度
    SQL语句中的日期计算
    注意Request.Cookies["UserID"]的用法
  • 原文地址:https://www.cnblogs.com/DDiamondd/p/10857605.html
Copyright © 2011-2022 走看看