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

来源:互联网 发布:美国大学学生会 知乎 编辑:程序博客网 时间:2024/06/05 08:26

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
95 2 1 5 2 1 5 2 141 2 3 40
 

Sample Output
65
 

Source
ACM暑期集训队练习赛(七)
 

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


原创粉丝点击