按字典序输出所有在123..n之间插入'+','-',' '结果为0的表达式。.

http://train.usaco.org/usacoprob2?a=jUh88pMwCSQ&S=zerosum

/*
TASK:zerosum
LANG:C++
*/
#include<cstdio>
#include<string>
#include<algorithm>
using namespace std;
#define N 15
int n;
int k[N],cnt,s[3]={0,1,-1};
string ans[7000];
void dfs(int d){
    if(d>n){
        int sum=0,c=1;
        for(int i=2;i<=n;i++){
            if(k[i]){
                sum+=c;
                c=i*k[i];
            }else{
                c=c*10+(c>0?i:-i);
            }
        }
        sum+=c;
        if(sum==0){
            ans[++cnt]+="1";
            for(int i=2;i<=n;i++){
                ans[cnt]+=k[i]>0?'+':k[i]<0?'-':' ';
                ans[cnt]+=i+'0';
            }
        }
        return;
    }
    for(int i=0;i<=2;i++){
        k[d]=s[i];
        dfs(d+1);
    }
}
int main(){
    freopen("zerosum.in","r",stdin);
    freopen("zerosum.out","w",stdout);
    scanf("%d",&n);
    dfs(2);
    for(int i=1;i<=cnt;i++){
        printf("%s\n",ans[i].c_str());
    }
}

 

 

 

  


┆凉┆暖┆降┆等┆幸┆我┆我┆里┆将┆ ┆可┆有┆谦┆戮┆那┆ ┆大┆始┆ ┆然┆
┆薄┆一┆临┆你┆的┆还┆没┆ ┆来┆ ┆是┆来┆逊┆没┆些┆ ┆雁┆终┆ ┆而┆
┆ ┆暖┆ ┆如┆地┆站┆有┆ ┆也┆ ┆我┆ ┆的┆有┆精┆ ┆也┆没┆ ┆你┆
┆ ┆这┆ ┆试┆方┆在┆逃┆ ┆会┆ ┆在┆ ┆清┆来┆准┆ ┆没┆有┆ ┆没┆
┆ ┆生┆ ┆探┆ ┆最┆避┆ ┆在┆ ┆这┆ ┆晨┆ ┆的┆ ┆有┆来┆ ┆有┆
┆ ┆之┆ ┆般┆ ┆不┆ ┆ ┆这┆ ┆里┆ ┆没┆ ┆杀┆ ┆来┆ ┆ ┆来┆