Sticks
| Time Limit: 1000MS | Memory Limit: 10000K | |
| Total Submissions: 100998 | Accepted: 22982 |
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
Source
DFS+剪枝.TLE了十几遍A了。
根据代码解释吧。
Code:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int num[65];
bool vis[65];
int sum,n,ans;
bool flag;
void dfs(int id,int a,int s)
{
if(flag) return ; //如果找到答案便返回。
if(s<a) return; //这句要不要好像无所谓
if(!a&&!s) //当最后一次找到的木棍恰好满足ans的长度并且总长度也满足是,标记为1,返回。
{
flag=1;
return ;
}
else if(!a) //找到一次ans,但还有剩余,继续搜索
{
dfs(0,ans,s);
return;
}
if(s==ans) //如果剩余量就等于ans,标记为1,返回,这句好像也无所谓
{
flag=1;
return;
}
int pre=-1; //标记搜索过的长度,避免搜索相同的长度,这个是我最早的剪枝
for(int i=id; i<n; i++)
{
if(!vis[i]&&pre!=num[i]&&a>=num[i]&&s>=num[i])
{
vis[i]=1;
pre=num[i];
dfs(i+1,a-num[i],s-num[i]);
vis[i]=0;
if(a==num[i]) return ; //下面三句参考网上的,少两句就会TLE
if(a==ans) return ; //搜一次,不管有没有正确答案,都返回,没必要继续搜,下一句同理
if(s==sum) return;
}
}
}
bool cmp(int a,int b)
{
return a>b;
}
int main()
{
while(scanf("%d",&n)!=EOF&&n)
{
sum=0;
flag=0;
memset(vis,0,sizeof(vis));
for(int i=0; i<n; i++)
{
scanf("%d",&num[i]);
sum+=num[i];
}
sort(num,num+n,cmp);
//for(int i=0; i<n; i++)
//cout<<num[i]<<" ";
ans=num[0];
while(!flag)
{
while(sum%ans!=0) ans++; //组合出来的木棍的长度只可能为总长度的约数,这句也很重要
//cout<<ans<<endl;
dfs(0,ans,sum);
ans++;
}
printf("%d\n",ans-1);
}
return 0;
}
1505

被折叠的 条评论
为什么被折叠?



