这个题目是北大上面深度优先遍历的经典算法,主要的减枝策略是对数组进行排序,在每次搜索时一定要把第一个放进去。地址:
http://acm.pku.edu.cn/JudgeOnline/problem?id=1011
#include <stdio.h>
#include <stdlib.h>
int stick[64];
int used[64];
int n, m, len;
void init ( int n )
{
for ( int i=1; i<n; i++ )
{
used[i] = 0;
}
used[0] = 1;
}
int cmp ( const void *a, const void *b )
{
return *( int * )b - *( int * )a;
}
int dfs ( int start, int no, int cur, int last )
{
int i, j;
if ( ! last )
{
if ( cur == len )
{
return 1;
}
return 0;
}
if ( cur == len )
{
if ( m - no > last )
{
return 0;
}
for ( i=1; i<n; i++ )
{
if ( ! used[i] )
{
break;
}
}
used[i] = 1;
if ( dfs ( i+1, no+1, stick[i], last-1 ) )
{
return 1;
}
used[i] = 0;
return 0;
}
else
{
if ( m - no > last - 1 )
{
return 0;
}
for ( i=start; i<n; i++ )
{
if ( ! used[i] && cur+stick[i] <= len )
{
used[i] = 1;
if ( dfs ( i+1, no, cur+stick[i], last-1 ) )
{
return 1;
}
used[i] = 0;
for ( j=i+1; j<n; j++ )
{
if ( stick[i] != stick[j] )
{
break;
}
}
i = j - 1;
}
}
return 0;
}
}
int main ()
{
int max, sum;
while ( scanf ( "%d", &n ) != EOF && n )
{
sum = 0;
max = -1;
for ( int i=0; i<n; i++ )
{
scanf ( "%d", &stick[i] );
sum += stick[i];
if ( stick[i] > max )
{
max = stick[i];
}
}
qsort ( stick, n, sizeof ( int ), cmp );
m = n + 1;
init (n);
while ( -- m )
{
if ( ( ! ( sum % m ) ) && ( ( sum / m ) >= max ) )
{
len = sum / m;
if ( dfs ( 1, 1, stick[0], n-1 ) )
{
break;
}
}
}
printf ( "%d\n", len );
}
return 0;
}