首页 > 代码库 > HDU 1455——Sticks(神棍)

HDU 1455——Sticks(神棍)

这题跟 HDU1518差不多


附上测试数据~~


64
40 40 30 35 35 26 15 40 40 40 40 40 40 40 40 40 40 40 40 40 40 
40 40 43 42 42 41 10 4 40 40 40 40 40 40 40 40 40 40 40 40 40 
40 25 39 46 40 10 4 40 40 37 18 17 16 15 40 40 40 40 40 40 40 40


46
40 37 32 10 47 4 42 56 61 23 59 36 27 16 16 37 26 19 14 29 31 58 51 32 63 28 11 25 12 15 39 42 46 43 11 19 53 17 39 21 45 44 8 23 51 55 


58
57 6 44 4 16 35 54 9 32 23 43 55 46 41 8 41 55 44 31 59 57 58 59 29 53 30 3 39 52 17 32 45 8 40 34 18 20 11 32 33 14 41 31 25 4 42 54 9 29 37 47 29 34 20 47 56 61 5 


26
3 64 18 49 4 40 18 61 50 36 17 49 8 17 62 11 24 8 36 59 34 26 28 7 37 26 


12
1 1 2 2 2 3 3 3 3 3 3 4


27
15 3 2 4 11 1 8 8 8 15 3 2 4 11 1 8 8 8 15 3 2 4 11 1 8 8 8


9
15 4 3 1 2 8 11 8 8


45
15 3 2 11 4 1 8 8 8 15 3 2 11 4 1 8 8 8 15 3 2 11 4 1 8 8 8 15 3 2 11 4 1 8 8 8
15 3 2 11 4 1 8 8 8
0


答案:

454
89
89
99
6
20
20
20


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<functional>
#define M 100
using namespace std;
int n,m,sum,flag,vis[M],a[M];

void dfs(int s,int cur,int d,int p,int q)
{
    if(cur==p||flag){
        flag=1;
        return ;
    }
    for(int i=s;i<n;++i){

        if(vis[i]||(d+a[i]>q)) continue;
        vis[i]=1;
        if(d+a[i]==q) dfs(0,cur+1,0,p,q);
        else dfs(i+1,cur,d+a[i],p,q);

        vis[i]=0;

        if(flag) return ;

        if(d==0) break;//剪枝
        while(a[i+1]==a[i]) i++;//如果性质相同,剪枝 

    }
    return ;
}

int main()
{
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    while(scanf("%d",&n),n){
        sum=0;
        for(int i=0;i<n;++i){
            scanf("%d",&a[i]);
            sum+=a[i];
        }
        sort(a,a+n,greater<int>() );

        for(int i=a[0];i<=sum;++i){
            if(sum%i) continue;
            memset(vis,0,sizeof vis);
            flag=0;
            dfs(0,0,0,sum/i,i);
            if(flag){
                cout<<i<<endl;break;
            }
        }

    }
    return 0;
}