/*
    ID:chenjiong
    PROG:zerosum
    LANG:C++
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char ans[20];
int N;

char tmp[9][9];
int x,y;

void init()
{
    int i;
    for ( i = 0; i < N; i++)
        ans[2 * i] = i + 1 + '0';
    ans[N + N - 1] = '\0';
}

void pre()
{
    int i;
    tmp[x][y++] = '1';
    for ( i = 1; i <= N + N - 3; i += 2)
    {
        switch ( ans[i] )
        {
            case '+' : tmp[x][y] = '\0'; x++; y = 0; tmp[x][y++] = ans[i + 1]; break;
            case '-' : tmp[x][y] = '\0'; x++; y = 0; tmp[x][y++] = ans[i + 1]; break;
            case ' ' : tmp[x][y++] = ans[i + 1]; break;
        }
    }
    tmp[x][y] = '\0';
    x++;
}


void dfs(int cur)
{
    if ( cur == N )
    {
        x = y = 0;
        pre();
        
        int i;
        int sum = atoi(tmp[0]);
        int p = 1;
        for ( i = 1; i <= N + N - 3; i += 2)
        {
            switch ( ans[i] )
            {
                case '+' : sum += atoi(tmp[p++]); break;
                case '-' : sum -= atoi(tmp[p++]); break;
                case ' ' : break;
            }
        }
        
        if ( sum == 0 )
            printf("%s\n",ans);
            
        
        return;
    }

    ans[2 * cur - 1] = ' ';
    dfs(cur + 1);

    ans[2 * cur - 1] = '+';
    dfs(cur + 1);

    ans[2 * cur - 1] = '-';
    dfs(cur + 1);

}

int main()
{
    freopen("zerosum.in","r",stdin);
    freopen("zerosum.out","w",stdout);

    scanf("%d",&N);
    init();
    dfs(1);

    return 0;
}

 

posted on 2012-11-13 15:37  Sinker  阅读(121)  评论(0编辑  收藏  举报