(周六赛1)Sum it up

题意:

Sample Input
4 6 4 3 2 2 1 1
5 3 2 1 1
400 12 50 50 50 50 50 50 25 25 25 25 25 25
0 0

Sample Output
Sums of 4:
4
3+1
2+2
2+1+1
Sums of 5:
NONE
Sums of 400:
50+50+50+50+50+50+25+25+25+25
50+50+50+50+50+25+25+25+25+25+25

注意每个数只能用一次,且不能出现重复的等式

题解 :dfs深搜

 1 #include<stdio.h>
 2 int a[20],ans[20];
 3 int sum,n,flag;
 4 void dfs(int x,int count,int m)
 5 {
 6     int last,i;
 7     if(m>sum)
 8     return;
 9     if(m==sum)
10     {
11         flag=1;
12         for(i=1;i<count;i++)
13         {
14             if(i==count-1)
15                 printf("%d\n",ans[i]);
16             else
17                 printf("%d+",ans[i]);
18         }
19     }
20     last=-1;
21     for(i=x;i<=n;i++)
22     {
23         if(last!=a[i])
24         {
25             ans[count]=a[i];
26             last=a[i];
27             dfs(i+1,count+1,m+a[i]);
28         }
29     }
30     return;
31 }
32 
33 int main()
34 {
35     int i;
36     while(~scanf("%d %d",&sum,&n))
37     {
38         if(sum==0&&n==0)
39             break;    
40         for(i=1;i<=n;i++)
41             scanf("%d",&a[i]);
42         flag=0;
43         printf("Sums of %d:\n",sum);
44         dfs(1,1,0);
45         if(!flag)
46         puts("NONE");        
47     }
48     return 0;
49 }

 

posted @ 2015-02-03 11:10  江豚  阅读(125)  评论(0编辑  收藏  举报