dfs+剪枝

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<algorithm>
#include<cstring>
using namespace std;
int a[100];
int used[100];
int ans;
int n;
int dfs(int pos,int len,int cnt)  //当前位置,当前组合长度,当前木棒数
{
    if(!len&&cnt>=n) return 1; //木棒数>n并且当前长度不为0直接返回 收索完成
    int last=-1;
    for(int i=pos;i>=0;--i)   //
    {
        if(used[i]||a[i]==last)  continue;  //如果该木棒已经被使用 或者和上一个长度相同 就跳过
        used[i]=1;                            //标记搜过
        if(len+a[i]==ans)                    
            if(dfs(pos-1,0,cnt+1)) return 1;//当前长度+当前木棒刚好等于ans就搜 下一组
            else last=a[i];                
        else if (len+a[i]<ans)            //加上当前长度还不够,就往下试下一根
            if(dfs(pos,a[i]+len,cnt+1)) return 1;
            else last=a[i];
        used[i]=0;        //回溯
        if(len==0) break;
    }
    return 0;
}

int main()
{
    while(cin>>n&&n)
    {
        memset(used,0,sizeof used);
        int sum=0;
        for(int i=0;i<n;i++)
            {
                cin>>a[i];
                sum+=a[i];
            }
        sort(a,a+n);  
        for(ans=a[n-1];ans<=sum;ans++)
            if((sum%ans==0)&&dfs(n-1,0,0)) break;  //从最长的开始搜
        cout<<ans<<endl;

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/codetypeman/article/details/79987645