Sticks dfs and pruning

George took a set of wooden sticks of equal length and chopped them off at random to obtain several small sticks, and the length of each stick did not exceed 50 units. Then he wanted to splice these sticks together and restore them to the state before cutting, but he forgot how many sticks there were at the beginning and the initial length of the sticks. Please design a program to help George calculate the minimum possible length of the stick. The length of each stick is represented by an integer greater than zero.
The input contains multiple sets of data, and each set of data includes two rows. The first line is an integer no more than 64, indicating how many knots of sticks there are after cutting. The second line is the length of each section of the stick after truncation. After the last set of data. Is a zero.
For each set of data, output the smallest possible length of the original wooden stick.
Input and output example
Input
9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0
Output
6
5
Sort the sticks from large to small. The length of the sticks must be a factor of the sum of all sticks.
Small stick

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[1001],len,cnt;
int book[1001],n;
bool cmp(int a,int b)
{
    
    
    return a>b;
}
int dfs(int l,int k,int m)//剩余的长度,第几根,几组
{
    
    
    if(m==cnt)
        return 1;
    if(l==0)
        if(dfs(len,0,m+1))
            return 1;
    int i;
    for(i=k;i<n; i++)
    {
    
    
        if(book[i]==0&&a[i]<=l)
        {
    
    
            book[i]=1;
            if(dfs(l-a[i],i+1,m))
            return 1;
            book[i]=0;
            if(l==a[i]||l==len)
                break;
  /*若l==a[i],说明剩余的长度和当前木棍长度一样,
  但却不能和剩余的木棍组合在一起完成拼接,说明这木棍会被剩余,
  则之前已经组合好的木棍要重新组合。*/
  /*若l==len,说明利用当前木棍拼接时没有完成拼接,
  则这个木棍会被剩下,则之前已经组合好的木棍要重新组合。*/
            int tmp=a[i];
            while(tmp==a[i]&&i<n)
                ++i;
        }
    }
    return 0;
}
int main()
{
    
    
    int i,sum=0;
    scanf("%d",&n);
    for(i=0; i<n; i++)
    {
    
    
        scanf("%d",&a[i]);
        sum+=a[i];
    }
    sort(a,a+n,cmp);
    for(len=a[0]; len<sum; len++)
    {
    
    
        if(sum%len==0)
        {
    
    
            cnt=sum/len;
            if(dfs(len,0,0))
                break;
        }
    }
    printf("%d\n",len);
}

Guess you like

Origin blog.csdn.net/m0_46312382/article/details/107570862