欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

poj1011Sticks(搜索+剪枝)

程序员文章站 2024-03-23 21:40:34
...

Sticks
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 145596 Accepted: 34453
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

题意:现在有短枝参差不齐若干个,不知原长,不知原数量,求最短的原短枝长度(原短枝长度均相同)。

搜索,将所有短枝从大到小排序求出MAX,则能出现的原短枝len必是处在(MAX,sum)之间,然后从大到小枚举短枝,搜索其与剩下所有的短枝匹配,若出现能让sum%len为0的len,且能让搜出的匹配数u=n时,则输出当前len。

剪枝:剪除相邻长度相同且不能与前一len匹配的短枝,例如10,7,7,7,7 ,7,6,5。由于10与7匹配后并不能被sum%now_len=0,则将后面所有的相同的短枝跳过搜索。

#include<iostream>
#include<algorithm>
#include <cstdio>
#include <cstring>
using namespace std;

int n,a[110];
int vist[110];

int flag;
int cmp(int a,int b)
{
    return a>b;
}
int len;
void dfs(int s,int now_len,int u)
{
    if(flag)
    return;
    if(now_len==0)
    {
        int k=0;
        while(vist[k])k++;
        vist[k]=1;
        dfs(s+1,a[k],k+1);
        vist[k]=0;
        return;
    }
    if(now_len==len)
    {
        if(s==n)
        {
            flag=1;
            return;

        }
        else dfs(s,0,0);
        return;
    }
    for(int i=u;i<n;i++)
    {
        if(!vist[i]&&now_len+a[i]<=len)
        {
            if(!vist[i-1]&&a[i]==a[i-1]) continue;
            vist[i]=1;
            dfs(s+1,now_len+a[i],i+1);
            vist[i]=0;
        }
    }
    return;
}
int main()
{
    while(scanf("%d",&n)!=EOF&&n)
    {
        int sum=0;
        flag=0;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
            sum+=a[i];
        }
        sort(a,a+n,cmp);
        for(len=a[0];len<sum;len++)
        {
            if(sum%len==0)
            {
                memset(vist,0,sizeof(vist));
                dfs(0,0,0);
                if(flag)break;
            }
        }
        cout<<len<<endl;
    }
    return 0;
}