PKU1011“Stick”这道我的想法是贪心加深搜。两重递归,可惜超时了!

最近几天看了深搜和递归的算法,于是乎实战用了一下。这个程序我改了很久,最后用了两重的递归,可以遍历所有的解,我想过了,其实可以加个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;
 }
}

 

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值