您的位置:首页 > 其它

POJ 1011 Sticks

2016-01-14 18:26 260 查看
寒假决定开始刷题了,写这道题主要是为了克服内心的恐惧感…大一的时候学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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: