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;
 }
}

 

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章