hdu 1258 Sum It Up dfs

刚开始做的时候没有发现这道题目的坑人之处,就按照普通的方法去写,其实搜索的时候注意一下去重就可以了,

先把所给的数排序,当找到一个合适的值后,要找与这层值不一样的再向下递归,

 

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <cstdlib>
 4 
 5 #define N 15
 6 int sum, n, vis[N], a[N], b[N], flag;
 7 
 8 int cmp (const void *a, const void *b)
 9 {
10     return *(int *)b - *(int *)a;
11 }
12 void dfs (int x, int y, int z);
13 
14 int main ()
15 {
16     while (scanf ("%d %d", &sum, &n), n)
17     {
18         for (int i=0; i<n; i++)
19             scanf ("%d", &a[i]);
20         qsort (a, n,sizeof(a[0]), cmp);
21 
22         memset (vis, 0, sizeof(vis));
23         flag  = 1;
24         printf ("Sums of %d:\n", sum);
25         dfs(0, 0, 0);
26         
27         if ( flag )
28             printf ("NONE\n");
29     }
30     return 0;
31 }
32 
33 void dfs (int x, int y,int z)
34 {
35     if (y > sum)
36         return ;
37     if (y == sum)
38     {
39         flag = 0;
40         for (int i=0; i<x; i++)
41             printf ("%d%c", b[i], i==x-1?'\n':'+');
42         return;
43     }
44 
45     for (int i=z; i<n; i++)
46     {
47         if ( !vis[i] )
48         {
49             vis[i] = 1;
50             b[x] = a[i];
51             dfs(x+1, y+a[i], i+1);
52             vis[i] = 0;
53             while (a[i] == a[i+1])//去重
54                 i++;
55         }
56     }
57 }

 

posted @ 2014-10-15 13:57  罗茜  阅读(172)  评论(0编辑  收藏  举报