题目链接:http://poj.org/problem?id=1564
题目大意:给定一个整数t,和n个元素组成的集合。求能否用该集合中的元素和表示该整数,如果可以输出所有可行解。1<=n<=12
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
分析:
代码如下:
1 # include<cstdio> 2 # include<iostream> 3 # include<algorithm> 4 using namespace std; 5 bool cmp(int a,int b){ 6 return a>b; 7 } 8 int a[15],t,n; 9 bool flag; 10 int ans[15],len; 11 12 void dfs(int sum,int mark){ 13 int i; 14 if(sum == 0){ 15 flag = true; 16 printf("%d",ans[0]); 17 for(i=1;i<len;i++) 18 printf("+%d",ans[i]); 19 printf(" "); 20 return; 21 } 22 if(sum<0 || mark>=n) return ; 23 for(i=mark; i<n; i++){ 24 if(i==mark || a[i] != a[i-1]){ 25 ans[len++] = a[i]; 26 dfs(sum-a[i],i+1); 27 len--; 28 } 29 } 30 } 31 int main(){ 32 int i; 33 while(scanf("%d%d",&t,&n) && n){ 34 int temp = 0; 35 for(i=0;i<n;i++){ 36 scanf("%d",&a[i]); 37 temp += a[i]; 38 } 39 printf("Sums of %d: ",t); 40 if(temp<t){ 41 printf("NONE "); 42 continue; 43 } 44 flag = false; 45 len = 0; 46 sort(a,a+n,cmp); 47 dfs(t,0); 48 if(!flag) 49 printf("NONE "); 50 51 } 52 return 0; 53 }