首页 > 搜索 > DFS搜索 > HDU 1455 Sticks-DFS-[解题报告] C++
2013
12-11

HDU 1455 Sticks-DFS-[解题报告] C++

Sticks

问题描述 :

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.

输入:

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.

输出:

The output file contains the smallest possible length of original sticks, one per line.

样例输入:

9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0

样例输出:

6
5

讲的大致是几根原本长度相同的木棒,然后被某人当出气筒剪啊剪啊,剪成好几段,然后,好吧,这时间一长记性就差了,忘了原来这堆木棒的长度。。。orz,我这若菜,也只能帮您推算出原来这堆木棒的可能的最短长度了。。。

搜索中的经典之经典,必须掌握啊。。。。

 

#include<iostream>
 #include<cstring>
 #include<algorithm>
 using namespace std;
 
 struct stick{
     int length;  //长度
     int mark;  //标记是否被使用过
 };
 stick sticks[64];
 int n,num,sum;
 
 int cmp(const stick &s1,const stick &s2){
     return s1.length>s2.length;
 }
 //len当前的长度,count当前长度为len的木棒的根数
 int dfs(int len,int l,int count,int pos){
     if(len==sum)return 1;//如果当期的长度就是所有木棒的总长
     if(count==num)return 1;
     for(int i=pos;i<n;i++){
         if(sticks[i].mark)continue;
         //没有被标记过的
         if(len==(sticks[i].length+l)){
             sticks[i].mark=1;
             if(dfs(len,0,count+1,0))//长度相等时,还是要从第一根开始搜
                 return 1;
             sticks[i].mark=0;
             return 0;
         }else if(len>(sticks[i].length+l)){
             sticks[i].mark=1;
             l+=sticks[i].length;
             if(dfs(len,l,count,i+1))
                 return 1;
             l-=sticks[i].length;//如果不成功,就要恢复
             sticks[i].mark=0;
             if(l==0)return 0;//当前搜索,如果前面的l为0,但第一根没有用上,那么这根木棒就要舍弃
             while(sticks[i].length==sticks[i+1].length)i++;//这根不成功的话,则相连的长度相同的不要
         }
     }
     return 0;
 }
 
 int main(){
     while(scanf("%d",&n)!=EOF){
         if(n==0)break;
         sum=0;
         for(int i=0;i<n;i++){
             scanf("%d",&sticks[i].length);
             sticks[i].mark=0;
             sum+=sticks[i].length;
         }
         sort(sticks,sticks+n,cmp);
         for(int len=sticks[0].length;len<=sum;len++){
             if(sum%len)continue; 
             num=sum/len; //原来长度为len的木棒的根数
             if(dfs(len,0,0,0)){
                 printf("%d\n",len);
                 break;
             }
         }
     }
     return 0;
 }

 

解题报告转自:http://www.cnblogs.com/wally/archive/2013/01/28/2880128.html


,
  1. 第二块代码if(it != mp.end())应改为if(it != mp.end() && (i+1)!=(it->second +1));因为第二种解法如果数组有重复元素 就不正确