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+表达式的计算(字符串的处理)
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;
}