以前做过,不过是是看着别人代码做的。今天手痒重新做一遍,两处剪枝还是没想到。还有,我真是快爱死了深搜+回溯。

#include <stdio.h>
#include <string.h>
#include <algorithm>

using namespace std;

const int MAXN = 64;

int N;
int s[MAXN];
bool vis[MAXN];
int len;

int used;
int rest;

bool dfs(int num)
{
    if ( used == N && rest == 0 )
        return true;
    for (int i = 0; i < N; i++)
    {    
        if ( !vis[i] && s[i] <= rest )
        {
            vis[i] = true;
            used++;
            rest -= s[i];
        
            if ( rest == 0 && used < N )
            {
                rest = len;
                if ( dfs(num + 1) )
                    return true;
                vis[i] = false;
                used--;
                rest = s[i];
                break;
            }
            else
            {
                if ( dfs(num) )
                    return true;
                vis[i] = false;
                used--;
                rest += s[i];
                if ( rest == len )
                    break;
                while ( s[i + 1] == s[i] )
                    i++;
            }
        }
    }
    return false;
}

bool cmp(const int& x,const int& y)
{
    return x > y;
}

int main()
{
//    freopen("1.txt","r",stdin);

    while ( scanf("%d",&N) == 1 )
    {
        if ( N == 0 )
            break;
        
        int sum = 0;
        for (int i = 0; i < N; i++)
        {
            scanf("%d",&s[i]);
            sum += s[i];
        }

        sort(s,s + N,cmp);

        for ( len = s[0]; len <= sum; len++)
        {
            if ( sum % len == 0 )
            {
                memset(vis,0,sizeof(vis));
                rest = len;
                used = 0;

                if ( dfs(0) )
                {
                    printf("%d\n",len);
                    break;
                }
            }
        }
    }

    return 0;
}
            

            


                

 

posted on 2012-10-20 01:20  Sinker  阅读(150)  评论(0编辑  收藏  举报