Sticks
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 118252 | Accepted: 27269 |
Description
Input
Output
Sample Input
9 5 2 1 5 2 1 5 2 1 4 1 2 3 4 0
Sample Output
6 5
Source
题意:原来有多根长度相同的棒子,被随机折成最长为50的n根棒子,给出n和折后的个棒子长度,求原来棒子最小可能长度。
dfs,几个剪枝:
直接复制的别人的剪枝(传送门)。。
POJ2362的强化版,重点在于剪枝
令InitLen为所求的最短原始棒长,maxlen为给定的棒子堆中最长的棒子,sumlen为这堆棒子的长度之和,那么InitLen必定在范围[maxlen,sumlen]中
根据棒子的灵活度(棒子越长,灵活度越低) DFS前先对所有棒子降序排序
剪枝:
1、 由于所有原始棒子等长,那么必有sumlen%Initlen==0;
2、 若能在[maxlen,sumlen-InitLen]找到最短的InitLen,该InitLen必也是[maxlen,sumlen]的最短;若不能在[maxlen,sumlen-InitLen]找到最短的InitLen,则必有InitLen=sumlen;
3、 由于所有棒子已降序排序,在DFS时,若某根棒子不合适,则跳过其后面所有与它等长的棒子;
4、 最重要的剪枝:对于某个目标InitLen,在每次构建新的长度为InitLen的原始棒时,检查新棒的第一根stick[i],若在搜索完所有stick[]后都无法组合,则说明stick[i]无法在当前组合方式下组合,不用往下搜索(往下搜索会令stick[i]被舍弃),直接返回上一层
#include <stdio.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <queue>
#include <set>
using namespace std;
//#define WIN
#ifdef WIN
typedef __int64 LL;
#define iform "%I64d"
#define oform "%I64d\n"
#define oform1 "%I64d"
#else
typedef long long LL;
#define iform "%lld"
#define oform "%lld\n"
#define oform1 "%lld"
#endif
#define S64I(a) scanf(iform, &(a))
#define P64I(a) printf(oform, (a))
#define S64I1(a) scanf(iform1, &(a))
#define P64I1(a) printf(oform1, (a))
#define FOR(i, s, t) for(int (i)=(s); (i)<(t); (i)++)
const int INF = 0x3f3f3f3f;
const double eps = 10e-9;
const double PI = (4.0*atan(1.0));
const int maxn = 64 + 10;
int sticks[maxn];
int vis[maxn];
int n, sum, ans;
bool cmp(int a, int b) {
return a > b;
}
bool dfs(int cur, int now) {
if(now == ans) {
if(cur == sum/ans) return true;
else return dfs(cur+1, 0);
}
int lastl = -1;// 剪枝,
for(int i=0; i<n; i++) if(!vis[i] && now + sticks[i] <= ans && lastl != sticks[i]) {
vis[i] = 1;
bool t = dfs(cur, now+sticks[i]);
vis[i] = 0;
if(t) return true;
lastl = sticks[i];
if(now == 0 && !t) return false;// 剪枝
}
return false;
}
int main() {
while(scanf("%d", &n) != EOF && n) {
sum = 0;
for(int i=0; i<n; i++) {
scanf("%d", &sticks[i]);
sum += sticks[i];
}
sort(sticks, sticks+n, cmp);
int maxL = sticks[0];
int flag = 1;
for(int i=maxL; i<=sum-i; i++) if(sum % i == 0) { //剪枝
ans = i;
memset(vis, 0, sizeof(vis));
bool res = dfs(1, 0);
if(res) {
flag = 0;
break;
}
}
if(flag) ans = sum;
printf("%d\n", ans);
}
return 0;
}