POJ1011

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值