(POJ1950)Dessert-DFS

Description

FJ has a new rule about the cows lining up for dinner. Not only must the N (3 <= N <= 15) cows line up for dinner in order, but they must place a napkin between each pair of cows with a "+", "-", or "." on it. In order to earn their dessert, the cow numbers and the napkins must form a numerical expression that evaluates to 0. The napkin with a "." enables the cows to build bigger numbers. Consider this equation for seven cows: 

      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

One line with a single integer, N

Output

One line of output for each of the first 20 possible expressions -- then a line with a single integer that is the total number of possible answers. Each expression line has the general format of number, space, napkin, space, number, space, napkin, etc. etc. The output order is lexicographic, with "+" coming before "-" coming before ".". If fewer than 20 expressions can be formed, print all of the expressions.

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

題目分析:

題目大意就是在數中插入‘+’或‘-’或‘.’使得最後式子計算出來的結果爲0。

不同情況對應的圖大概就像上圖的情況,用DFS枚舉每層符號的不同情況,對不同的情況進行DFS,當deepth==N時,看計算出來的和是不是0。是0並且當前式子在第二十個以內就輸出。最後在輸出一個個數。

#include<iostream>
#include<string>
using namespace std;
int N;
int m = 0;
char expp[16];

void print() {
	int i = 0;
	for (i = 1; i < N; i++) {
		cout <<i<<" "<< expp[i]<<" ";
	}
	cout << i << endl;
}
void DFS(int deepth, int sum,int pre) {
	if (deepth == N) {
		if (sum == 0) {
			m++;
			
			if (m <= 20) {
				print();
			}
		}
	}
	else {
		
		int next;		//代表下一層的深度,同時也代表下一層是哪個數
		//第一種情況爲+
		expp[deepth] = '+';	//當前層後面的符號,例如deepth = 2,那麼2後面的符號爲+,+號後面的數爲deepth+1
		next = deepth + 1;
		DFS(deepth + 1, sum + next, next);
		//第二種情況爲-
		expp[deepth] = '-';
		next = deepth + 1;
		DFS(deepth + 1, sum - next, next);
		//第三種情況爲.
		expp[deepth] = '.';
		if (deepth < 9) {
			next = pre * 10 + deepth + 1;
		}
		else {
			next = pre * 100 + deepth + 1;
		}
		int i = deepth - 1;
		while (expp[i] == '.'&&i >= 0)i--;			//例0+1+2.3.4. 找到不爲點的那個符號i = 1
		if (expp[i] == '+') {
			DFS(deepth + 1, sum + next - pre, next);
		}
		else if (expp[i] == '-')
		{
			DFS(deepth + 1, sum - next + pre,  next);
		}
	}
}

int main() {
	cin >> N;
	expp[0] = '+';		//表示0+1?2?。。。。
	m = 0;
	DFS(1, 1, 1);
	cout << m << endl;
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章