Time Limit: 1000MS | Memory Limit: 30000K | |
Description
1 - 2 . 3 - 4 . 5 + 6 . 7
This means 1-23-45+67, which evaluates to 0. You job is to assist the cows in getting dessert. (Note: "... 10 . 11 ...") will use the number 1011 in its calculation.)
Input
Output
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 6
Source
#include<iostream>
using namespace std;
const int Max = 16;
int n,num; // num記錄可能得情況數。
char symbol[Max];
void print()
{
int i;
for(i = 1; i < n; i ++)
printf("%d %c ", i, symbol[i]);
printf("%d\n", i);
}
void dfs(int sum, int depth, int pre) // dfs儘量少用全局變量,如定義成dfs(int depth)。
{
if(depth == n) // 深搜出口。
{
if(sum == 0)
{
num ++;
if(num <= 20) print();
}
}
else
{
int next;
symbol[depth] = '+'; // 若第depth位符號爲'+'。
next = depth + 1;
dfs(sum + next, depth + 1, next);
symbol[depth] = '-'; // 若第depth位符號爲'-'。
next = depth + 1;
dfs(sum - next, depth + 1, next);
symbol[depth] = '.'; // 若第depth位符號爲'.'。
if(depth < 9)
next = pre * 10 + depth + 1;
else
next = pre * 100 + depth + 1;
int i = depth - 1;
while(symbol[i] == '.' && i >= 0) i --;
if(symbol[i] == '+')
dfs(sum + next - pre, depth + 1, next);
else if(symbol[i] == '-')
dfs(sum - next + pre, depth + 1, next);
}
}
int main()
{
cin >> n;
symbol[0] = '+'; // 將第0個符號看成'+',構造成 0 + 1 ? 2 ? 3 …簡化後面較煩的初始化。
num = 0;
dfs(1, 1, 1);
cout << num << endl;
return 0;
}