//usaco-zero sum /* * 类型:搜索 * 深度搜索所有的情况,记录符合条件的符号集 * !!!空格符号的处理,需确定当前数已经读完 * 读到空格处理当前数据,读到'+'或'-'处理前面的数据 * sum记录前面算式的值,tmp记录当前数据 * c记录上一操作符,cc记录当前操作符 */ #include <iostream> #include <fstream> #include <algorithm> using namespace std; #define MAX 1000 int k,n; char chh[4]="+- "; struct node{ char ch[10];}p[MAX],a; void dfs(int sum,int tmp,int i,char c,char cc) { int j; if(cc=='+' || cc=='-'){ if(c=='+'){ sum+=tmp; tmp=i; } else{ sum-=tmp; tmp=i; } c=cc; } else tmp=tmp*10+i; if(i==n){ if((c=='+' && sum+tmp==0) || (c=='-') && sum-tmp==0) p[k++]=a; return ; } for(j=0; j!=3; ++j){ a.ch[i-1]=chh[j]; dfs(sum,tmp,i+1,c,chh[j]); } } int cmp(node x,node y) { for(int i=0; i!=n; ++i) if(x.ch[i]!=y.ch[i]) return x.ch[i]<y.ch[i]; return 0; } int main(void) { int i,j; ifstream fin("zerosum.in"); ofstream fout("zerosum.out"); fin>>n; dfs(0,0,1,'+','+'); sort(p,p+k,cmp); for(i=0; i!=k; ++i){ fout<<"1"; for(j=2; j<=n; ++j) fout<<p[i].ch[j-2]<<j; fout<<endl; } return 0; }