poj 1011

来源:互联网 发布:手机c语言编辑器 编辑:程序博客网 时间:2024/05/15 23:48

       一道传说中很经典的搜索+剪枝的题。

       我主要用了三个剪枝,前两个很容易想到,代码里有注释看看就明白,这里主要说说第三个剪枝。在拼凑某根stick的第一节a时失败了,就直接结束,返回到上一个stick的循环中去,因为part a一定属于某一个stick,但是如果当前没匹配上,那么之后也不会匹配上,也就是说最终一定失败,所以就立即返回。

      我的第三个剪枝,要感谢下面这篇博文:POJ1011-Sticks - ζёСяêτ - 小優YoU。

代码(C++):

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#define MAX 52#define INF (1<<30)using namespace std;int stick[MAX],slen,llen;bool dfs(int len,int nlen,int sum){    int i,m;    if(sum==0) return true;    m=len-nlen>llen?llen:len-nlen;  //剪枝2:从剩余长度的位置开始枚举    for(i=m;i>=slen;i--)    {        if(stick[i]==0) continue;        stick[i]--;        if(nlen+i==len)        {            if(dfs(len,0,sum-i)) return true;        }else if(nlen+i<len){            if(dfs(len,nlen+i,sum-i)) return true;        }        stick[i]++;        if(nlen==0) break;    //剪枝3:在拼凑某根stick的第一节时失败了,就直接结束    }    return false;}int main(){    //freopen("in.txt","r",stdin);    int n,i,sum,id;    while(scanf("%d",&n)&&n!=0)    {        memset(stick,0,sizeof(stick));        llen=sum=0;        slen=INF;        for(i=0;i<n;i++)        {            scanf("%d",&id);            stick[id]++;            sum+=id;            llen=max(llen,id);            slen=min(slen,id);        }        for(i=llen;i<=sum;i++)        {            if(sum%i==0)    //剪枝1:所枚举的stick的长度必须为总长度的约数            {                if(dfs(i,0,sum)) break;            }        }        printf("%d\n",i);    }    return 0;}

题目(http://poj.org/problem?id=1011):

Sticks
Time Limit: 1000MS Memory Limit: 10000K   

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

95 2 1 5 2 1 5 2 141 2 3 40

Sample Output

65

0 0
原创粉丝点击