码迷,mamicode.com
首页 > 其他好文 > 详细

Sum It Up -- 深搜 ---较难

时间:2016-03-28 13:33:06      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

技术分享技术分享

每一行都是一组测试案例   第一个数字 表示总和 第二个数字表示 一共有几个可用数据  现在 按照从小到大的顺序   输出  那些数字中若干数字之和为总和的  信息 /.

很好很明显的  遍历痕迹 , 多看多练

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<math.h>
 4 #include<iostream>
 5 #include<algorithm>
 6 #include<queue>
 7 #include<vector>
 8 #include<set>
 9 #include<stack>
10 #include<string>
11 #include<sstream>
12 #include<map>
13 #include<cctype>
14 using namespace std;   //  输入的时候  就是 有序的 .
15 int a[1005],flag,n,m,vis[1005],res[1005]={1005};
16 void DFS(int m,int cnt)
17 {
18     int i;
19     if(m==0)    // 攒够了之后
20     {
21         flag=1;
22         for(int j=1;j<cnt-1;j++)
23             printf("%d+",res[j]);
24         printf("%d\n",res[cnt-1]);
25         return ;
26     }
27     for(int i=1;i<=n;i++)
28     {
29         if(!vis[i]&&m-a[i]>=0&&a[i]<=res[cnt-1])  //
30         {
31             vis[i]=1;
32             res[cnt]=a[i];
33             DFS(m-a[i],cnt+1);
34             vis[i]=0;
35             while(a[i]==a[i+1]&&i<=n)
36                 ++i;
37         }
38     }
39 }
40 int main()
41 {
42     while(scanf("%d%d",&m,&n),(n||m))
43     {
44         for(int i=1;i<=n;i++)
45             scanf("%d",&a[i]);
46         flag=0;
47         printf("Sums of %d:\n",m);
48         memset(vis,0,sizeof(vis));
49         DFS(m,1);
50         if(!flag)
51             printf("NONE\n");
52     }
53     return 0;
54 }

 

Sum It Up -- 深搜 ---较难

标签:

原文地址:http://www.cnblogs.com/A-FM/p/5328624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!