岳麓山上打水 DFS+完全背包

样例1

样例输入1[复制]

16
3
3
5
7

样例输出1[复制]

2 3 5

限制

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include<set>
#include <assert.h>
#include<iostream>
using namespace std;
int dp[210000];
int ans[210000];
int cnt;
int a[210000];
bool flag[210000];
int vol,n;
int tuichu;

bool solve()
{
memset(dp,0,sizeof(dp));
for(int i = 1; i < cnt; i ++)
{
for(int j = ans[i]; j <= vol; j ++)
{
dp[j] = max(dp[j - ans[i]] + ans[i],dp[j]);
}
}
if(dp[vol]==vol)  return  true;
return false;
}

bool dfs(int dangqian,int mubiao)
{
if(dangqian>=mubiao)
{
if(solve())
{
tuichu=1;
cout<<cnt-1<<" ";
for(int i=1;i<cnt-1;i++)
{
cout<<ans[i]<<" ";
}
cout<<ans[cnt-1]<<endl;

}
return 1;
}
for(int i = 1; i <= n; i ++)
{
if(flag[i])
continue;
flag[i]=1;
ans[cnt++] = a[i];
dfs(dangqian+1,mubiao);
if(tuichu)
return 1;
cnt--;
flag[i]=0;
}
}

int main()
{
cin>>vol>>n;
tuichu=0;
cnt=1;
for(int i = 1; i <= n; i ++)
cin>>a[i];
memset(flag,0,sizeof(flag));
sort(a+1,a+n+1);
for(int i = 1; i <= n; i ++)
{
if(dfs(0,i))
{
break;
}
}
return 0;
}