码迷,mamicode.com
首页 > 其他好文 > 详细

Sticks_dfs

时间:2016-10-31 21:56:15      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:algo   sed   size   lines   stream   ssi   iostream   turn   design   

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 should 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

 

【题意】给出n个长度的短棒,是由原来等长的小棒任意剪切而来,问原来的小棒最短的长度是多少

【思路】用dfs搜索,重点是其中的几个剪枝,不减的话会超时。

 

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
const int N=105;
int n;
int d,num;
int val[N];
int vis[10005];
bool flag;
int cmp(int x,int y)
{
    return x>y;
}
void dfs(int k,int len,int num1)
{
    if(flag==1) return ;
    if(len==d)
    {
        dfs(0,0,num1+1);
        if(flag==1) return ;
    }
    if(num1==num)
    {
        flag=1;
        return ;
    }
    for(int i=k;i<=n;i++)
    {
        if(!vis[i]&&len+val[i]<=d)
        {
            vis[i]=1;
            dfs(i+1,len+val[i],num1);
            vis[i]=0;
            if(len==0) return ;

//如果当前搜索时,前面的长度为0,而第一根没有使用,说明第一根始终要废弃,这种组合必然不会成功

            if(len+val[i]==d) return ;
            if(val[i]==val[i+1]) i++;

//如果当前和上一次搜到的木棒一样长,就没必要再搜了


        }
    }

}
int main()
{
    while(~scanf("%d",&n),n)
    {
        int sum=0;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&val[i]);
            sum+=val[i];
        }
        sort(val+1,val+1+n,cmp);
        for(int i=val[1];i<=sum;i++)
        {
            if(!(sum%i))
            {
                flag=0;
                memset(vis,0,sizeof(vis));
                d=i;
                num=sum/d;
                dfs(0,0,0);
                if(flag==1) break;
            }
        }
        printf("%d\n",d);
    }

    return 0;
}

 

Sticks_dfs

标签:algo   sed   size   lines   stream   ssi   iostream   turn   design   

原文地址:http://www.cnblogs.com/iwantstrong/p/6017227.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!