poj 1950 回溯

n个数,+、-、.号等于0的等式 输出等式和总过的等式

#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;

const int MAXN=20;

const int MAXM=16;

char str[MAXM],opt[MAXN][MAXM];

int n,cnt;

void dfs(int deep,int num,int pre)
{
	int now,k;

	if(deep==n)
	{
		str[n]='\0';
		if(num==0)
		{
			if(cnt<MAXN)
			{
				strcpy(opt[cnt],str);
			}
			cnt++;
		}
	}
	else
	{
		str[deep-1]='+';
		dfs(deep+1,num+deep+1,deep+1);

		str[deep-1]='-';
		dfs(deep+1,num-deep-1,deep+1);

		str[deep-1]='.';//如果是.号的话要计算now,分情况讨论

		if(deep+1>=10)
			now=100*pre+deep+1;
		else
			now=10*pre+deep+1;

		int j=deep-1;

		while(str[j]=='.'&&j>=0)j--;

		if(j<0)
			k=now;
		else if(str[j]=='+')k=num+now-pre;
		else k=num-now+pre;

		dfs(deep+1,k,now);
	}
}

int main()
{
	int i,j;

	while(scanf("%d",&n)!=EOF)
	{
		cnt=0;

		dfs(1,1,1);

		for(i = 0; i < cnt; i ++) {

			if(i == MAXN) break;

			for(j = 0; opt[i][j]; j ++)

				printf("%d %c ", j + 1, opt[i][j]);

			printf("%d\n", n);

		}

		printf("%d\n", cnt);

	}

	return 0;
}

  

posted @ 2012-04-13 23:28  shijiwomen  阅读(319)  评论(0编辑  收藏  举报