poj3628

dfs

View Code
   
     
#include < iostream >
#include
< cstdio >
#include
< cstdlib >
#include
< cstring >
using namespace std;

#define maxn 25

int n, m;
int f[maxn], s[maxn];
int ans;

void dfs( int cow, int sum)
{
if (ans == 0 )
return ;
if (s[cow] + sum < m)
return ;
if (sum >= m)
{
ans
= min(ans, sum - m);
return ;
}
if (cow == n)
return ;
dfs(cow
+ 1 , sum);
dfs(cow
+ 1 , sum + f[cow]);
}

int main()
{
// freopen("t.txt", "r", stdin);
scanf( " %d%d " , & n, & m);
for ( int i = 0 ; i < n; i ++ )
scanf(
" %d " , & f[i]);
s[n]
= 0 ;
for ( int i = n - 1 ; i >= 0 ; i -- )
s[i]
= s[i + 1 ] + f[i];
ans
= 0x3f3f3f3f ;
dfs(
0 , 0 );
printf(
" %d\n " , ans);
return 0 ;
}

你可能感兴趣的:(poj)