Usaco 2.3 Zero Sums(回溯DFS)--暴搜

Zero Sum

Consider the sequence of digits from 1 through N (where N=9) in increasing order: 1 2 3 ... N.

Now insert either a `+' for addition or a `-' for subtraction or a ` ' [blank] to run the digits together between each pair of digits (not in front of the first digit). Calculate the result that of the expression and see if you get zero.

Write a program that will find all sequences of length N that produce a zero sum.

PROGRAM NAME: zerosum

INPUT FORMAT

A single line with the integer N (3 <= N <= 9).

SAMPLE INPUT (file zerosum.in)

7

OUTPUT FORMAT

In ASCII order, show each sequence that can create 0 sum with a `+', `-', or ` ' between each pair of numbers.

SAMPLE OUTPUT (file zerosum.out)

1+2-3+4-5-6+7
1+2-3-4+5+6-7
1-2 3+4+5+6+7
1-2 3-4 5+6 7
1-2+3+4-5+6-7
1-2-3-4-5+6+7

每层只有3个状态,直接暴搜。。
k是层数,sum和num分别表示最终累加和和当前每一步的累加结果。。。。
/*
ID:shi13891
LANG:C++
PROG:zerosum
*/
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>

using namespace std;
 

char a[1000];
int n;
 

void DFS(int k,int sum,int num)
{
    if(k==n)
    {
        if(sum+num==0)
        puts(a);
        return;
    }
    if(a[2*k-1]=' ')
    DFS(k+1,sum,num>0?num*10+k+1:num*10-k-1);
    if(a[2*k-1]='+')
    DFS(k+1,sum+num,k+1);
    if(a[2*k-1]='-')
    DFS(k+1,sum+num,-k-1);
}

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


    while(cin>>n)
    {
        memset(a,0,sizeof(a));
        for(int i=0;i<n;i++)
        {
            a[2*i]=i+'1';
        }
        DFS(1,0,1);
    }
    fclose(stdin);
    fclose(stdout);
    return 0;
}


你可能感兴趣的:(Usaco 2.3 Zero Sums(回溯DFS)--暴搜)