最近几天看了深搜和递归的算法,于是乎实战用了一下。这个程序我改了很久,最后用了两重的递归,可以遍历所有的解,我想过了,其实可以加个flag,找到就跳出,但是我失败了。我觉得解决的关键应该是剪枝或者用新的算法。至于如何剪枝,我想还要继续想想它的约束条件!
我的代码:
///*
//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 "algorithm"
using namespace std;
int num[100];
int flag[100];
int sum,mins,n;
void finds(int,int,int);
bool isfull(int flag[])
{
int i;
for(i=0;i<n;i++)
if(!flag[i])
return false;
return true;
}
void func(int i,int n,int sum1)
{
int j;
if(!flag[n-1])
{
sum+=num[n-1];
flag[n-1]=1;
finds(i+1,n,sum1);
}
for(j=0;j<n-1;j++)
{
if(!flag[j])
{
sum+=num[j];
flag[j]=1;
finds(i+1,n,sum1);
func(i,n,sum1);
sum-=num[j];
flag[j]=0;
}
}
}
void finds(int i,int n,int sum1)
{
int j;
if(sum==sum1&&isfull(flag))
{
if(mins>sum)
mins=sum;
return;
}
if(sum==sum1&&i)
{
sum1=0;
i++;
}
for(j=0;j<n-1;j++)
{
if(!flag[j])
{
sum1+=num[j];
flag[j]=1;
finds(i,n,sum1);
sum1-=num[j];
flag[j]=0;
}
}
return;
}
int main()
{
int i;
while(cin>>n&&n)
{
memset(num,0,sizeof(num));
memset(flag,0,sizeof(flag));
sum=0;
mins=1<<20;
for(i=0;i<n;i++)
cin>>num[i];
sort(num,num+n);
func(0,n,0);
cout<<mins<<endl;
}
}