hdu 1258 DFS

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1258
题目描述:给你一个数t作为最后等式的和,并给你一组数a[i](i<12)作为等式的加数,每个加数最多只能使用一次,要求输出所有满足条件(加数从大到小输出)的等式,并且不能重复。
例:t=4. a[]={4,3,2,2,1,1}
输出 4,3+1,2+2,2+1+1
解题思路:题目要求输出从大到小输出,所以可以先给所有的数进行降序排序。数据的规模很小,所以可以用暴力搜索。搜索过程中,为了避免重复输出,需要记录前一层搜索的起点,下一层递归搜索的起点不能与前一层记录的点一样...说不清楚,具体见代码

 

#include <iostream> #include <algorithm> using namespace std; int t,n; int a[20]; int save[20]; int index; int used[20]; int sign; int cmp(const int &a, const int& b) { return a > b; } void dfs(int k, int sum) { if(sum > t) { return ; } if(sum == t) { sign = 1; for(int i=0; i<index-1; i++) { cout<<save[i]<<"+"; } cout<<save[index-1]<<endl; return ; } int last = -1; for(int i=k+1; i<=n; i++) { if(a[i] != last) //当前的数不能跟上一次搜索的起点的数值一样,不然会造成重复 { save[index++] = a[i]; last = a[i]; //last保存当前搜索的起点 dfs(i,sum+a[i]); index--; } } } int main() { int i; while(cin>>t>>n,t+n) { index = 0; sign = 0; for(i=1; i<=n; i++) { cin>>a[i]; } sort(a+1,a+n+1,cmp); //降序排序 printf("Sums of %d:/n",t); dfs(0,0); if(!sign) { cout<<"NONE"<<endl; } } return 0; }

你可能感兴趣的:(hdu 1258 DFS)