poj 1011 Sticks 经典的深搜(dfs)+ 强剪枝

Sticks
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 131671   Accepted: 30906

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
4
1 2 3 4
0

Sample Output

6
5

题意:就是一些棍子,让你求出最小长度的值;
思路:看见就激动了,深搜的问题啊,写着写着就开始不懂啦,看了别人的博客,也懂了,总结主要有下面几点:
     1.最小长度一定在所给棍子最长的和总长之间,并且最小长度可以整除总长;
     2.对棍子进行一次从大到小的排序,短的棍子可以灵活的使用
     3.对于排序号的棍子,如果前后相同那就没必要在搜一次了,
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
int a[100];//存棍子
int visit[100];
int tol;//总长
int n;
int sum;//表示最小长度
int tag;
int num;//表示有几个最小长度

int cmp(int a,int b) {
    return a > b;
}

int  dfs(int s,int pos,int cnt) {//s表示当前组合的长度,pos表示访问的下标,cnt表示计数
    if(cnt == num) {
        return 1;
    }//组合成的棍子数目等于num
    else if(s == sum){
        return dfs(0,0,cnt+1);
    }//当前长度满足了棍子最小长度cnt++;
    else{
            int pre,i;//pre表示前一个长度,
        for(i = pos,pre = 0; i < n; i++) {
            if(!visit[i] && a[i] != pre && a[i]+s <= sum ) { //没有被访问过,并且避免当前的和前面的如果一样就没必要在搜这个,当前值+上现在的长度 《= 最小长度;
                pre = a[i];
                visit[i] = 1;
                if(dfs(s+a[i],i+1,cnt)){break;}
                visit[i] = 0;
                if(pos == 0) {
                    return 0;
                }
            }
        }
            if(i == n){return 0;}
            else return 1;
    }
}

int main() {
    while(~scanf("%d",&n) && n) {
        tol = 0;
        for(int i = 0; i < n; i++) {
            scanf("%d",&a[i]);
            tol += a[i];
        }
        sort(a,a+n,cmp);
        for(sum = a[0]; sum <= tol; sum++) {
            if(tol % sum == 0) {
                memset(visit,0,sizeof(visit));
                num = tol/sum;
                 tag = dfs(0,0,0);
                if(tag) {
                    printf("%d\n",sum);
                    break;
                }
            }
        }
    }
    return 0;
}

小结:好久没有好好做题了,感觉陷入了低谷,没有办法从头再写,发现这些题还是写不来,简直是状态差的很,看见了别人写的博客,感觉是那样,自己却写不出来,心里满满的是恨
现在要拾起来重新来过,相信每个人都应该坚持那个最初的梦想,都应该向阳生长,不应该这样沉沦,期待自己的状态越来越好。。相信自己就好!!!!
 

你可能感兴趣的:(poj 1011 Sticks 经典的深搜(dfs)+ 强剪枝)