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

时间:2023-11-17 17:54:44

题意:首先给你一个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[] ;
int save[] ;
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=;j<count-;j++)
{
printf("%d+",save[j]);
}
printf("%d\n",save[count-]);
flag = ;
return ;
}
for (int i = pos ; i < n ; i++)
{
save[count] = a[i] ;
dfs (count+,L+a[i] , i+) ;
while (a[i] == a[i+])
i++ ;
} } int main()
{
//freopen("in.txt","r",stdin) ; while (scanf("%d %d" , &t , &n) != EOF)
{
if (t == && n == )
break ;
int i ;
for (i = ; i < n ; i++)
{
scanf("%d" , &a[i]) ;
}
sort(a,a+n,cmp) ;
flag = ;
printf("Sums of %d:\n",t);
dfs(,,) ;
if (flag == )
{
printf("NONE\n") ;
}
} return ; }