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.
9 5 2 1 5 2 1 5 2 1 4 1 2 3 4 0
6 5
题意是有n个木棒,他们由相同的长度的若干木棒切开得到,求最小的原始木棒长度。
首先对给出的木棒长度从大到小排序,这样就可以从小到大枚举原始长度,此时根据总长度就可以得到原始根数,(若枚举根数超时)。
对于当前枚举的长度,从大到小依次去尝试选取木棒,若长度小于等于目标长度,则加入,同时标记使用。若达到了目标长度,则将得到根数+1,若根数达到目标根数的时候,则为可行方案。
#include<bits/stdc++.h>
using namespace std;
int n;
int a[105];
int vis[105];
int aim, target;
bool cmp(int a, int b)
{
return a>b;
}
bool dfs(int cnt, int cur, int pos)// 目标根数, 完成根数, 当前长度
{
if(cnt == target) return 1;
if(cur == aim) return dfs(cnt+1, 0, 0);
for(int i = pos; i < n; ++i)
{
if(!vis[i] && cur+a[i]<=aim)
{
vis[i] = 1;
if(dfs(cnt, cur+a[i], i+1))
return 1;
vis[i] = 0;
if(cur == 0) return 0;
while(i+1 < n && a[i+1]==a[i]) i++;
}
}
return 0;
}
int main()
{
ios::sync_with_stdio(false);
while(cin >> n && n!=0)
{
int sum = 0;
for(int i = 0; i < n; i++)
{
cin >> a[i];
sum += a[i];
}
sort(a, a+n, cmp);
for(int i = 1; i <= sum; ++i)//枚举长度, 枚举根数TLE
if(sum%i == 0)//整除
{ //cout <<"ok"<< endl;
aim = i;
target = sum/i;
memset(vis, 0, sizeof(vis));
if(dfs(0, 0, 0))
{
cout << aim << endl;
break;
}
}
}
return 0;
}