《挑战程序设计竞赛》P30部分和问题

来源:互联网 发布:google earth 知乎 编辑:程序博客网 时间:2024/04/28 04:54
/*在原题的基础上增加了记录中间变量的过程保存中间量要注意在适当的地方记录*/#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 1000000const 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:41 2 4 713Sample Output:YES14 = 1 + 2 + 4 + 7*/

0 0