poj 1011 Sticks

//poj 1011 经典搜索题
//http://www.cnblogs.com/eclipse9614/archive/2010/05/24/POJ1011.html
//这位老兄解题报告的第三点是最强力的,不过要配合其他剪枝才能过,0MS。。。
#include <iostream>
#include <algorithm>

using namespace std;

int n,sum;
int len[70];
int mark[70];

bool dfs(int step,int now,int c,int from)
{
     if (step==n) return true;
     for(int i=from;i>=0;i--)
     if (!mark[i] && len[i]<=now )
     {
                  if (i<n-1 && c==now && !mark[i+1]) return false;  //剪枝1
                   mark[i]=1;
                  if (now==len[i])   //剪枝2
                  {
                             if(dfs(step+1,c,c,n-1)) return true;
                             mark[i]=0;
                             return false;
                  }
                  if (dfs(step+1,now-len[i],c,i-1)) return true;
                  mark[i]=0;
                while (i && len[i]==len[i-1]) --i;   //剪枝3
     }
     return false;
}

int main()
{
    while (scanf("%d",&n) && n)
    {
          sum=0;
          for (int i=0;i<n;i++) { scanf("%d",&len[i]); sum+=len[i]; }
          sort(len,len+n);
          for (int l=len[n-1];l<=sum;l++)
          if (sum%l==0)  //剪枝4
          {
             memset(mark,0,sizeof(mark));
             if (dfs(0,l,l,n-1))
               {
                     printf("%d/n",l);
                     break;
               }
          }
    }
    //system("pause");
    return 0;
}

你可能感兴趣的:(poj 1011 Sticks)