POJ 1011 Sticks

寒假决定开始刷题了,写这道题主要是为了克服内心的恐惧感…大一的时候学DFS的时候听这道题给吓傻了,各种剪枝的方法不知道从哪里入手,比较关键的剪枝应该是当组成一个新的木棒的第一个片段失败的时候,这个片段就永远都会失败,不会再次使用

另外再审题的时候出了一点问题,它说每个碎片的长度不超过50,我按照,木棍的长度不超过50写的,这道题因为保证一定有解所以设置长度搜索的上限的时候不需要有一个上限。

#include <iostream>
#include <cstdio>
#include <memory.h>
#include <algorithm>
using namespace std;

#define maxn 70

struct stick {
    int len;
    bool used;
};

bool operator < (stick a,stick b) {
    return a.len > b.len;
}

int n;
stick sticks[maxn]= {0};
int Sum = 0;
int num = 0;

bool DFS(int i,int cur,int cnt,int pos) {
    if(cnt==num)
        return true;

    for(int j=pos; j<n; ++j) {
        if(sticks[j].used)
            continue;

        if(cur+sticks[j].len==i) {
            sticks[j].used = true;
            if(DFS(i,0,cnt+1,0))
                return true;
            sticks[j].used = false;
            return false;
        } 
        else if(cur+sticks[j].len<i) {
            bool begin = false;
            if(!cur)
                begin = true;

            sticks[j].used = true;
            if(DFS(i,cur+sticks[j].len,cnt,j+1))
                return true;
            sticks[j].used = false;

            if(begin)
                return false;
            while(sticks[j].len == sticks[j+1].len)
                ++j;
        }
    }
    return false;
}

int main() {
    while(scanf("%d",&n),n) {
        memset(sticks,0,sizeof(sticks));
        Sum = 0;
        num = 0;

        for(int i=0; i<n; ++i) {
            scanf("%d",&sticks[i].len);
            Sum += sticks[i].len;
        }
        sort(sticks,sticks+n);


        for(int i=sticks[0].len;; ++i) {
            if(Sum%i)
                continue;
            num = Sum/i;
            if(DFS(i,0,1,0)) {
                printf("%d\n",i);
                break;
            }
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值