HDOJ1455 (DFS+剪枝优化)和 HDOJ1518可做类比

Sticks

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11007    Accepted Submission(s): 3342


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 file 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
 

Recommend
lcy   |   We have carefully selected several similar problems for you:   1312  1067  1045  1426  1181 


求原本木棍的最小可能长度,跟HDOJ 1518很相似,只不过木棍数目不确定。1518那题确定了木棍数目为4,因为要构成正方形。
这题中,读入长度之后从大到小排序,减少情况的判断。加几条剪枝优化,不然会超时。

#include <iostream>
#include <stdio.h>
#include <cmath>
#include <algorithm>
#include <string.h>
using namespace std;

const int maxn = 70;
int n,a[maxn],used[maxn],total,length,stick_num;

bool dfs(int num,int pos,int res){ //和HDOJ 1518深搜写法十分类似
    if(num==stick_num) return true;
    for(int i=pos;i<=n;i++){
        if(used[i]) continue;
        used[i] = true;
        if(a[i]==res){
            if(dfs(num+1,0,length)) return true;
        }
        else if(a[i]<res){
            if(dfs(num,i+1,res-a[i])) return true;
        }
        used[i] = false;
        if (res==length) return false; //没有找到合适的解,剪枝
        while (i+1<=n && a[i+1]==a[i]) i++; //如果二者相同,因为之前的深搜已经得出结论这条线走不通,所以直接排除掉再选一次相同数字的可能
    }
    return false;
}

int main(){
    while (cin>>n && n){
            total=0;
        for (int i=1;i<=n;i++) {
                cin>>a[i];
                total+=a[i];
        }
        sort(a+1,a+n+1,greater<int>()); //从大到小排序
        memset(used,0,sizeof(used));
        for (int i=1;i<=total;i++) if (total%i==0){
             stick_num=total/i;
             length=i;
             if (dfs(0,1,length)) {
                printf("%d\n",i);
                break;
             }
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值