输出一串数所能构成的所有等式,按照加数从大到小,算式从长到短排列
一开始因为无法按照要求输出纠结了好一阵~~最后看了大神的代码才发现只需要每次dfs规定长度就好了~
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include"cstdio" #include"cstring" #include"algorithm" #define MAXN 40 using namespace std; int num[MAXN],n,front,rear,ok; int stack[MAXN]; int cal() { int sum=0; for(int i=front;i<rear;i++) sum+=stack[i]; return sum; } void display() { for(int i=front;i<rear-1;i++) printf("%d+",stack[i]); printf("%d=%d\n",stack[rear-1],cal()); } bool find(int x) { int low=0,high=n-1,mid; while(high>=low) { mid=low+(high-low)/2; if(num[mid]==x) return true; else if(num[mid]>x) high=mid-1; else low=mid+1; } return false; } void dfs(int mark,int len) { for(int i=mark+1;i<n;i++) { if(i<n&&cal()+num[i]<=num[n-1]) { stack[rear++]=num[i]; if(rear-front==len&&find(cal())) {display();ok=0;} else dfs(i,len); rear--; } } } int main() { int t; scanf("%d",&t); while(t--) { ok=1; memset(stack,0,sizeof(stack)); memset(num,0,sizeof(num)); scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&num[i]); sort(num,num+n); for(int len=2;len<=n;len++) for(int i=0;i<n;i++) {front=rear=0;stack[rear++]=num[i];dfs(i,len);} if(ok) printf("Can't find any equations.\n\n"); else printf("\n"); } return 0; }