零式求和


Problem 39: 零式求和


Time Limit:1 Ms|   Memory Limit:128 MB
Difficulty:3

Description

请考虑一个由1到N(N=3, 4, 5 ... 9)的数字组成的递增数列:1 2 3 ... N。现在请在数列中插入“+”表示加,或者“-”表示减,抑或是“ ”表示空白(例如1-2 3就等于1-23),来将每一对数字组合在一起(请不在第一个数字前插入符号)。计算该表达式的结果并注意你是否得到了和为零。请你写一个程序找出所有产生和为零的长度为N的数列。  

Input

单独的一行表示整数N (3 <= N <= 9)。  

Output

按照ASCII码的顺序,输出所有在每对数字间插入“+”, “-”, 或 “ ”后能得到和为零的数列。  

Sample Input

7

Sample Output

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

分析:dfs+表达式的计算(字符串的处理)

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int n;
char dd[] = {' ', '+', '-'};

int call(int a, char ch, int b)
{
	switch(ch)
	{
	case '+': return a + b;
	case '-': return a - b;
	}
}

int cal(char str[])//计算表达式
{
	int len = strlen(str);
	int res = str[0] - '0';
	int i = 1;
	while (str[i] == ' ' && i < len)
	{
		res = res * 10 + str[i + 1] - '0';
		i += 2;
	}
	int j;
	for (j = i; j < len; j++)
	{
		if (str[j] == '+' || str[j] == '-')
		{
			int num = str[j + 1] - '0';
			int k = j + 2;
		    while (str[k] == ' ' && k < len)
			{
				num = num * 10 + str[k + 1] - '0';
				k += 2;
			}	
			res = call(res, str[j], num);
		}
	}
	return res;
}

void dfs(int num, char str[], int k)//num为符号在数组里的位置,k为确定第几个字符
{
	if (k == n)
	{
		char str1[20] = {0};
		strcpy(str1, str);
		str1[num - 1] = n + '0';
	//	puts(str1);
	//	getchar();
		int res = cal(str1);
	//	printf("%d\n", res);
	//	getchar();
		if (res == 0)
			puts(str1);
		return ;
	}
	for (int i = 0; i < 3; i++)
	{
		str[num - 1] = k + '0';
		str[num] = dd[i];
		dfs(num + 2, str, k + 1);
	}
}

int main()
{
	scanf("%d", &n);
	char str[20] = {0};
    dfs(1, str, 1);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值