#include <iostream>
#include<algorithm>
using namespace std;
int m,a[40],b[40],h;
void dfs(int d,int k,int s,int g){
int i,j,f;
if (d>g){
f=0;
for (j=k+1;j<=m;j++)
if (a[j]==s) {f=1;break;}
if (f) {
h=0;
cout<<b[1];
for (j=2;j<d;j++) cout<<'+'<<b[j];
cout<<'='<<s<<endl;
}
} else {
for (i=k+1;i<=m;i++){
b[d]=a[i];
if (s+b[d]>a[m]) break;//根据递增性剪枝
dfs(d+1,i,s+b[d],g);
}
}
}
int main()
{
int t,i,j;
cin>>t;
while (t--){
cin>>m;
for (i=1;i<=m;i++) cin>>a[i];//dfs常用剪枝技巧,排序
sort(a+1,a+m+1);
h=1;
for (j=2;j<=m-1;j++){//<span style="color: rgb(34, 34, 34); font-family: 'times new roman'; font-size: 17px; background-color: rgb(234, 235, 255);">由于要按等式长度递增顺序输出所有方案,枚举限制长度DFS</span>
for (i=1;i<=m;i++) {
b[1]=a[i];
dfs(2,i,b[1],j);
}
}
if (h) cout<<"Can't find any equations."<<endl;
cout<<endl;
}
return 0;
}
ZOJ 1204 Additive equations
最新推荐文章于 2017-07-19 09:46:00 发布