hdoj

http://acm.hdu.edu.cn/showproblem.php?pid=1258

关键点就是一次递归里面一样的数字只能选一次。

 1 #include <cstdio>
 2 #include <cstring>
 3 
 4 int n,t;
 5 int b[15],c[15];
 6 bool flag;
 7 void dfs(int k,int sum,int l)
 8 {
 9     if(sum==t)
10     {
11         for(int i=0;i<l-1;i++)
12             printf("%d+",c[i]);
13         printf("%d
",c[l-1]);
14         flag=1;
15         return;
16     }
17     int last=-1;
18     for(int i=k;i<n;i++)
19     {
20         if(sum+b[i]>t) continue;
21         if(b[i]!=last) //注意这个就好了
22         {
23             last=c[l]=b[i];
24             dfs(i+1,sum+b[i],l+1);
25         }
26     }
27 }
28 
29 int main()
30 {
31    // freopen("a.txt","r",stdin);
32     while(~scanf("%d%d",&t,&n))
33     {
34         if(n==0) break;
35         memset(c,0,sizeof(c));
36         flag=0;
37         for(int i=0;i<n;i++)
38             scanf("%d",&b[i]);
39         printf("Sums of %d:
",t);
40         dfs(0,0,0);
41         if(!flag) printf("NONE
");
42     }
43     return 0;
44 }

http://acm.hdu.edu.cn/showproblem.php?pid=1016

这题注意回溯就好。

 1 #include <cstdio>
 2 #include <cstring>
 3 int n,b[25];
 4 bool used[25];
 5 bool is_prime(int x)
 6 {
 7     if(x==1) return false;
 8     else if(x==2||x==3) return true;
 9     for(int i=2;i*i<=x;i++)
10         if(x%i==0) return false;
11     return true;
12 }
13 
14 void dfs(int k,int num)
15 {
16     if(num==n)
17     {
18         //printf("%d
",num);
19         if(is_prime(b[n]+b[1]))
20         {
21             //printf("%d
",k);
22             for(int i=1;i<n;i++)
23                 printf("%d ",b[i]);
24             printf("%d
",b[n]);
25         }
26         return;
27     }
28     for(int i=1;i<=n;i++)
29     {
30         if(!used[i]&&is_prime(b[num]+i))
31         {
32             used[i]=true;
33             b[num+1]=i;
34             //printf("%d %d
",i,num);
35             dfs(i,num+1);
36             used[i]=false;
37         }
38     }
39 }
40 
41 int main()
42 {
43    // freopen("a.txt","r",stdin);
44     int j=1;
45     while(~scanf("%d",&n))
46     {
47         memset(b,0,sizeof(b));
48         memset(used,0,sizeof(used));
49         printf("Case %d:
",j++);
50         b[1]=1;
51         used[1]=true;
52         dfs(1,1);
53         printf("
");
54     }
55     return 0;
56 }
原文地址:https://www.cnblogs.com/nowandforever/p/4518939.html