poj1011——Sticks(dfs+剪枝)

来源:互联网 发布:澳洲mac电脑学生打几折 编辑:程序博客网 时间:2024/05/21 15:40

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

给出一些小木棒,能组合成长度相同的一组木棒,求这组木棒的最小长度
没想到这道题也能用搜索,不过要剪掉很多情况才不会超时

#include <iostream>#include <cstring>#include <string>#include <vector>#include <queue>#include <cstdio>#include <set>#include <math.h>#include <algorithm>#include <queue>#include <iomanip>#include <map>#define INF 0x3f3f3f3f#define MAXN 1005#define Mod 99999999using namespace std;int stick[100],vis[100],len,n;bool cmp(int a,int b){    return a>b;}bool dfs(int i,int l,int r){    if(l==0)    {        r-=len;        if(r==0)            return true;        int i;        for(i=0; vis[i]; ++i);        vis[i]=1;        if(dfs(i+1,len-stick[i],r))            return true;        vis[i]=0;        r+=len;    }    else    {        for(int j=i; j<n; ++j)        {            if(j>0&&(stick[j]==stick[j-1]&&!vis[j-1])) //上一个相同长度的没有被用上,这一个肯定也不会用                continue;            if(!vis[j]&&l>=stick[j])            {                l-=stick[j];                vis[j]=1;                if(dfs(j,l,r))                    return true;                l+=stick[j];                vis[j]=0;            }        }    }    return false;}int main(){    while(~scanf("%d",&n)&&n)    {        memset(vis,0,sizeof(vis));        int sum=0;        for(int i=0; i<n; ++i)        {            scanf("%d",&stick[i]);            sum+=stick[i];        }        sort(stick,stick+n,cmp);        int flag=0;        for(len=stick[0]; len<=sum; ++len)        {            if(sum%len==0)            {                if(dfs(0,len,sum))                {                    printf("%d\n",len);                    flag=1;                    break;                }            }        }        if(!flag)            printf("%d\n",sum);    }    return 0;}
0 0