HDU - 1455 G - Sticks

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. 
InputThe 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. 
OutputThe 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

解題思路:
這其實就是dfs,但是直接dfs就會超時,要去剪枝,將所有的樹枝排序,如果第一個是不符合的,比如說需要達到的長度是10,當前的長度是8,但是後面序列裏,並沒有長度爲2的,那麼8後面的情況都不需要考慮了,然後還有一些基礎的剪枝

代碼:
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
int a[100];
int sum,maxx;
int t;
bool flag;
int vis[100];
bool cmp(int a,int b)
{
    return a>b;
}
int dfs(int need,int now,int pos,int num)
{
    if(flag)
    {
        return true;
    }
    if(num==t)
    {
        flag = true;
        return true;
    }
    for(int i = pos;i<t;i++)
    {
        if(!vis[i]&&a[i]+now<=need)
        {
            vis[i] = 1;
            if(now+a[i]==need)
                dfs(need,0,0,num+1);
            else dfs(need,a[i]+now,i+1,num+1);
            vis[i] = 0;
            if(now==0)
                return false;
            while(i+1<t&&a[i]==a[i+1])
                i++;
            if(flag)
                return true;
        }
    }
}
int main()
{
    while(cin>>t&&t!=0)
    {
        memset(vis,0,sizeof(vis));
        memset(a,0,sizeof(a));
        flag = false;
        sum = 0;
        maxx = 0;
        for(int i = 0;i<t;i++)
        {
           cin>>a[i];
           sum+=a[i];
           maxx = max(maxx,a[i]);
        }
        sort(a,a+t,cmp);
        if(maxx>sum-maxx)
        {
            cout<<sum<<endl;
            continue;
        }
        for(int i = maxx;i<=sum;i++)
        {
            if(sum%i==0)
            {
                dfs(i,0,0,0);
                if(flag)
                {
                    cout<<i<<endl;
                    break;
                }

            }

        }
    }
}


發佈了79 篇原創文章 · 獲贊 1 · 訪問量 8918
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章