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

Zero SumConsider 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分别表示最终累加和和当前每一步的累加结果。。。
#include
#include
#include
#include
using namespace std;
char a[1000];
int n,i;
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()
{
	while(cin>>n)
	{
		memset(a,0,sizeof(a));
		for(i=0;i<n;i++)
		{
			a[2*i]=i+'1';
		}
		DFS(1,0,1);
	}
	return 0;
}
posted @ 2014-10-16 19:39  NYNU_ACM  阅读(161)  评论(0编辑  收藏  举报