ACCEPT
//#include "stdafx.h"
#include"stdio.h"
#include"iostream"
#include
using namespace std;
int tem[33] = { 0 };//存放加数 以便输出
int i = 0;
int flag = 0;
int c_sum=0;
void dfs(set &c_iset, set::iterator c_iterator, int de, int num)//num为加数个数
{set::iterator set_iter1;if (num == 2)//两个加数时{for (set_iter1 = c_iterator, set_iter1++; *set_iter1 <*c_iset.rbegin(); set_iter1++)//set_iter1++,指向下一个、这里实现的是第二个加数{//c_sum = 0;tem[de] = *set_iter1;c_sum += tem[de];
// for (int k = 0; tem[k] != 0; k++)
// {
// c_sum = c_sum + tem[k];
// }if (c_iset.find(c_sum) != c_iset.end())//找到sum 成功可输出 {flag = 1;//成功标志printf("%d", tem[0]);for (int j = 1; tem[j] != 0; j++){printf("+%d", tem[j]);}printf("=%d
", c_sum);}if (c_sum >= *c_iset.rbegin())//结束,不必再继续递归下去{tem[de] = 0;//重置为0 ,已经输出过了return;}c_sum -= tem[de];//dfs(c_iset, set_iter1, de + 1);//到下一个数}}else{for (set_iter1 = c_iterator, set_iter1++; *set_iter1 <*c_iset.rbegin(); set_iter1++)//set_iter1++,指向下一个、这里实现的是第二个加数{tem[de] = *set_iter1;//减少一个数c_sum = 0;for (int k = 0; tem[k] != 0; k++){c_sum = c_sum + tem[k];}if (c_sum > *c_iset.rbegin())//超过最后一个没有必要再进行下去了{tem[de] = 0;return;}num--;dfs(c_iset, set_iter1, de + 1, num);num++;}}tem[de] = 0;//重置为0return;};int main(){int n, m, l ;setiset;set::iterator set_iter;//scanf("%d", &n);//多少组while (n-- > 0){scanf("%d", &m);//每组个数iset.clear();//清空for (int j = 0; j < m; j++){scanf("%d", &l);iset.insert(l);}flag = 0;for (int j = 2; j < m; j++)//加数个数从2到m-1个{for (set_iter = iset.begin(); *set_iter <* iset.rbegin(); set_iter++)//固定的第一个加数{c_sum = *set_iter;tem[0] = c_sum;i = 1;dfs(iset, set_iter, i,j);}}if (flag == 0){printf("Can't find any equations.
");}printf("
");}return 0;}
set 作为参数要引用&!
注意还原,调试非常好用!
虽然做出来一点意思了,但是不符合要求。。。顺序这个,是要考我们按层次递归么?太蠢了!
但是第一次按自己的意思写出了想要的递归,我舍不得删掉,要留着
t等我写出答案,再来。。。
#include "stdafx.h"
#include"stdio.h"
#include"iostream"
#include
using namespace std;
int tem[33] = { 0 };//存放加数 以便输出
int i = 0;
int flag = 0;
void dfs(set &c_iset, set::iterator c_iterator, int de)
{set::iterator set_iter1;for (set_iter1 = c_iterator, set_iter1++; set_iter1 != c_iset.end(); set_iter1++)//set_iter1++,指向下一个{int c_sum = 0;tem[de] = *set_iter1;for (int k = 0; tem[k] != 0; k++){c_sum = c_sum + tem[k];}if (c_iset.find(c_sum) != c_iset.end())//找到sum 成功可输出 {flag = 1;//成功标志printf("%d", tem[0]);for (int j = 1; tem[j] != 0; j++){printf("+%d", tem[j]);}printf("=%d
", c_sum);}if (c_sum >= *c_iset.rbegin())//结束,不必再继续递归下去{tem[de] = 0;//重置为0return;}dfs(c_iset, set_iter1, de + 1);}tem[de] = 0;//重置为0return;
};int main()
{int n, m, l, sum;setiset;set::iterator set_iter;//scanf("%d", &n);while (n-->0){scanf("%d", &m);iset.clear();//清空while (m > 0){scanf("%d", &l);iset.insert(l);m--;}flag = 0;for (set_iter = iset.begin(); set_iter != iset.end(); set_iter++){sum = *set_iter;tem[0] = sum;i = 1;dfs(iset, set_iter, i);}if (flag==0){cout << "Can't find any equations." << endl;}}return 0;
}