/*
在原题的基础上增加了记录中间变量的过程
保存中间量要注意在适当的地方记录
*/
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <set>
#include <cmath>
#include <stack>
#include <queue>
#include <cstring>
using namespace std;
#define ll long long
#define llu unsigned long long
#define INF 1000000
const int maxn = 1000;
int n,k;
int a[maxn];
int sum;
int ans[maxn];
int len;
bool dfs(int i,int sum)
{
if(i == n) return sum == k;
if(dfs(i+1,sum))
{
return true;
}
else if(dfs(i+1,sum+a[i]))
{
// 当下层递归返回值为真时,记录当前递归的a[i]
ans[len++] = a[i];//记录中间结果
// cout << i << " " << a[i] << endl;
return true;
}
return false;
}
void solve()
{
// len = 0;
// memset(ans,0,sizeof(ans));
if(dfs(0,0))
{
printf("YES\n");
printf("%d = ",k);
for(int i = len-1; i > 0; --i)
printf("%d + ",ans[i]);
printf("%d\n",ans[0]);
}
else printf("NO\n");
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif // ONLINE_JUDGE
while(scanf("%d",&n) == 1)
{
for(int i = 0; i < n; ++i)
{
scanf("%d",&a[i]);
}
scanf("%d",&k);
solve();
}
return 0;
}
/*
Sample Input:
4
1 2 4 7
13
Sample Output:
YES
14 = 1 + 2 + 4 + 7
*/
《挑战程序设计竞赛》P30部分和问题
最新推荐文章于 2022-01-20 01:22:36 发布