您的位置:首页 > 其它

hdu 1258 从n个数中找和为t的组合 (DFS)

2015-05-16 15:21 183 查看

题意:首先给你一个t,然后是n,后面输入n个数,然后让你求的是n个数中和为t的序列总共有多少种,把他们按从左到右的顺序输出来。

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 <cmath>
# include <iostream>
# include <cstring>
# include <algorithm>
using namespace std ;

int a[20] ;
int save[20] ;
int  n , t ;
bool flag ;

bool cmp(const int &x , const int &y)
{
return x > y ;
}

void dfs(int count , int L , int pos)
{
if (L > t)
return  ;
if (L == t)
{
for(int j=0;j<count-1;j++)
{
printf("%d+",save[j]);
}
printf("%d\n",save[count-1]);
flag = 1 ;
return  ;
}
for (int i = pos ; i < n ; i++)
{
save[count] = a[i] ;
dfs (count+1,L+a[i] , i+1) ;
while (a[i] == a[i+1])
i++ ;
}

}

int main()
{
//freopen("in.txt","r",stdin) ;

while (scanf("%d %d" , &t , &n) != EOF)
{
if (t == 0 && n == 0)
break ;
int i ;
for (i = 0 ; i < n ; i++)
{
scanf("%d" , &a[i]) ;
}
sort(a,a+n,cmp) ;
flag = 0 ;
printf("Sums of %d:\n",t);
dfs(0,0,0) ;
if (flag == 0)
{
printf("NONE\n") ;
}
}

return 0 ;

}
View Code

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: