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
相关文章推荐
- Sum It Up POJ 1564 HDU 杭电1258【DFS】
- hdu 1258 DFS
- hdu 1258 Sum It Up ( dfs )
- hdu 1258(DFS)
- hdu1258 dfs深搜
- (step4.3.4)hdu 1258(Sum It Up——DFS)
- hdu 1258 DFS
- 【DFS】poj 1564 Sum It Up(hdu 1258)
- hdu 2566 统计硬币 dfs 不能排除组合重复的情况 代码不完整
- HDU 1258(dfs)
- HDU 1258 Sum it up 搜索DFS
- poj1564 Sum It Up (zoj 1711 hdu 1258) DFS
- hdu 1015 Safecracker【dfs 排列组合】
- HDU 1258 DFS
- hdu 1716 排列2 dfs 组合
- HDU-1258(DFS搜索的问题)
- hdu 1258和ZJU 1711 Sum It Up(dfs经典索搜)
- poj1564 Sum It Up (zoj 1711 hdu 1258) DFS
- HDU 1258 Sum It Up (dfs)
- HDU 1258 Sum It Up(Dfs)