POJ 1564(HDU 1258 ZOJ 1711) Sum It Up(DFS)

题目链接: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 分析: 代码如下:
 # include<cstdio>
# include<iostream>
# include<algorithm>
using namespace std;
bool cmp(int a,int b){
return a>b;
}
int a[],t,n;
bool flag;
int ans[],len; void dfs(int sum,int mark){
int i;
if(sum == ){
flag = true;
printf("%d",ans[]);
for(i=;i<len;i++)
printf("+%d",ans[i]);
printf("\n");
return;
}
if(sum< || mark>=n) return ;
for(i=mark; i<n; i++){
if(i==mark || a[i] != a[i-]){
ans[len++] = a[i];
dfs(sum-a[i],i+);
len--;
}
}
}
int main(){
int i;
while(scanf("%d%d",&t,&n) && n){
int temp = ;
for(i=;i<n;i++){
scanf("%d",&a[i]);
temp += a[i];
}
printf("Sums of %d:\n",t);
if(temp<t){
printf("NONE\n");
continue;
}
flag = false;
len = ;
sort(a,a+n,cmp);
dfs(t,);
if(!flag)
printf("NONE\n"); }
return ;
}
上一篇:SV4 面向对象编程基础


下一篇:洗礼灵魂,修炼python(16)--列表进阶话题—>上节作业讲解+copy模块,浅拷贝,深拷贝