#include<iostream>
#include<stdio.h>
#include<string.h>
#include<functional>
#include<algorithm>
#include<fstream>
using namespace std;
int total, mx,sum;
int sticks[100];
bool used[100];
bool dfs(int tobuild, int localleft, int totalleft,int tr){
//tobuild表示尝试当前长度仍需要组成的木棒
//localleft表示组成这根木棒还需要的长度
//totalleft表示木棒剩余的木棒总长
if(localleft == 0){
tobuild -=1;
localleft = tr;
}
if(tobuild == 0)
return true;
if(totalleft < localleft)return false; //剩余长度不够组成一个
int temp = 100;
for(int i = 1; i <= total; ++i){
if(!used[i] && sticks[i] <= localleft && sticks[i] != temp){
used[i] = true;
temp = sticks[i];
if(dfs(tobuild,localleft-sticks[i],totalleft-sticks[i],tr)){
return true;
}
used[i] = false;
if(localleft == tr){
return false;
}
}
}
return false;
}
int main(){
// freopen("1.txt","r",stdin);
while(scanf("%d",&total)&&total){
mx = 0;
sum = 0;
memset(sticks,0,sizeof(sticks));
memset(used,0,sizeof(used));
for(int i = 1; i <= total;++i){
scanf("%d",&sticks[i]);
if(mx < sticks[i]){
mx = sticks[i];
}
sum += sticks[i];
}
sort(sticks+1,sticks+1+total,greater<int>());
for(int t = mx; t <= sum; ++t){
if(sum % t) continue;
else if(dfs(sum/t,t,sum,t)){
printf("%d\n",t);
break;
}
}
}
return 0;
}
基本思想是dfs,注意剪枝~否则会超时
poj 木棒
最新推荐文章于 2021-09-22 22:47:56 发布