Sticks
Problem 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
1 2 3 4
0
Sample Output
6
5
题意
有若干根同样长的木板,进行了若干次切割,剩下n块木板,每块长度已知,求最初的长度的最小值。
题解:
木板长度和为
s
u
m
sum
sum,枚举可能的初始木板长度
x
x
x,DFS判断是否存在合理解,使正好能拼成
s
u
m
/
x
sum/x
sum/x块木板。
DFS注意剪枝:
1.在搜索一块新的原木板时,第一块未使用的木板必用。
2.第一块之后的木板,应该从选择上一块木板的编号后开始寻找。
3.第一块木板尽量选大,可以减少搜索的选择。
#include<stdio.h>
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<map>
#include<vector>
#include<queue>
#include<iterator>
#define dbg(x) cout<<#x<<" = "<<x<<endl;
#define INF 0x3f3f3f3f
#define LLINF 0x3f3f3f3f3f3f3f3f
#define eps 1e-6
using namespace std;
typedef long long LL;
typedef pair<LL, int> P;
const int maxn = 72;
const int mod = 1000000007;
int n, m, num, sig, a[maxn], vis[maxn];
bool cmp(int a, int b);
void dfs(int x, int sg, int pos);
int main()
{
int i, j, k, sum;
while(scanf("%d", &n), n)
{
sum = 0;
for(i=0;i<n;i++){
scanf("%d", &a[i]);
sum += a[i];
}
sort(a, a+n, cmp);
for(i=1;i<=sum;i++)
if(sum%i==0 && i>=a[0]){
num = sum/i, m = i;
sig = 0;
memset(vis, 0, sizeof(vis));
vis[0] = 1;
dfs(m-a[0], 0, 0);
if(sig)break;
}
printf("%d\n", i);
}
return 0;
}
bool cmp(int a, int b)
{
return a>b;
}
void dfs(int x, int sg, int pos)
{
if(sig)return ;
if(x == 0){
if(sg >= num-1)sig = 1;
else{
for(int i=0;i<n;i++)
if(!vis[i]){
vis[i] = 1;
dfs(m-a[i], sg+1, i+1);
vis[i] = 0;
break;
}
}
return;
}
int up = -1;
for(int i=pos;i<n;i++)
if(!vis[i] && x>=a[i] && up != a[i]){
vis[i] = 1;
dfs(x-a[i], sg, pos+1);
vis[i] = 0;
up = a[i];
}
}