杭电1258 Sum it Up DFS 搜索
来源:互联网 发布:大数据 文化产业 编辑:程序博客网 时间:2024/06/16 04:49
题目描述:给你一个数t作为最后等式的和,并给你一组数a[i](i<12)作为等式的加数,每个加数最多只能使用一次,要求输出所有满足条件(加数从大到小输出)的等式,并且不能重复。
例:t=4. a[]={4,3,2,2,1,1}
输出 4,3+1,2+2,2+1+1
例:t=4. a[]={4,3,2,2,1,1}
输出 4,3+1,2+2,2+1+1
解题思路:题目要求输出从大到小输出,所以可以先给所有的数进行降序排序。数据的规模很小,所以可以用暴力搜索。搜索过程中,为了避免重复输出,需要记录前一层搜索的起点,下一层递归搜索的起点不能与前一层记录的点一样
#include <iostream>#include <algorithm>#include <stdio.h>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;}
0 0
- 杭电1258 Sum it Up DFS 搜索
- 杭电 搜索 1258 Sum It Up
- Sum It Up POJ 1564 HDU 杭电1258【DFS】
- HDU 1258 Sum it up 搜索DFS
- 杭电--1258 深度搜索(sum it up)
- 杭电 HDU 1258 Sum It Up
- 杭电1258 Sum It Up
- hdu 1258 Sum It Up(DFS)
- hdoj 1258 Sum It Up(DFS)
- hdu 1258 Sum It Up(dfs)
- hdu 1258 Sum It Up(dfs)
- hdu 1258 Sum It Up dfs
- HDU 1258 Sum It Up DFS
- HDU--1258:Sum It Up (DFS)
- hdu 1258 Sum It Up (dfs)
- hdu 1258 Sum It Up(dfs)
- HDU 1258 Sum It Up (DFS)
- hdoj 1258 Sum It Up【DFS】
- Qt与C#之间的代码移植细节--慢慢的
- FreeMarker入门案例
- Netty教程-Channel
- 回溯法
- 1073: 人民币问题
- 杭电1258 Sum it Up DFS 搜索
- 高通常见缩写
- 依赖注入那些事儿好文章
- 数组指针 指针数组
- Odoo 创建主题
- 指针数组
- SSH demo 简单解析之“增删改”
- FTP 文件上传下载/读取
- matplotlib画图坐标轴设置