# POJ1950总结

## Dessert

### 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.

`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```

### 我的代码

``````for (int i=0;i<3;i++){
opes[step]=ope[i];
if (i<2){
dfs(caculate(preNum,nowNum,preOpe),step+2,step+1,ope[i]);
}else{
dfs(preNum,caculate(nowNum,step+2,ope[i]),step+1,preOpe);
}
}``````

``````#include<stdio.h>

const char ope[3]={'+','-','.'};
int n,ans;
char opes[20];

int caculate(int a,int b,char o){
switch(o){
case '+':
return a+b;
case '-':
return a-b;
case '.':
if(b>=10){
return a*100+b;
}else{
return a*10+b;
}

}
}

//int caculateAll(){
//	long long int preNum=0,nowNum=1;
//	char preOpe='+';
//	for (int i=0;i<n-1;i++){
//		if (opes[i]=='+'||opes[i]=='-'){
//			preNum=caculate(preNum,nowNum,preOpe);
//			nowNum=i+2;
//			preOpe=opes[i];
//		}else{
//			nowNum=caculate(nowNum,i+2,'.');
//		}
//	}
//	return caculate(preNum,nowNum,preOpe);
//}

void print(){
for (int i=1;i<=4*n-3;i++){
if (i%2==0){
printf(" ");
}else{
if (i%4==1){
printf("%d",i/4+1);
}else if (i%4==3){
printf("%c",opes[i/4]);
}
}
}
printf("\n");
}

void dfs(int preNum,int nowNum,int step,char preOpe){
if (step==n-1){
if (caculate(preNum,nowNum,preOpe)==0){
ans++;
if (ans<=20){
print();
}
}
}else{
if (preNum>100000000||nowNum>100000000) return;
for (int i=0;i<3;i++){
opes[step]=ope[i];
if (i<2){
dfs(caculate(preNum,nowNum,preOpe),step+2,step+1,ope[i]);
}else{
dfs(preNum,caculate(nowNum,step+2,ope[i]),step+1,preOpe);
}
}
}
}

int main()
{
ans=0;
scanf("%d",&n);
dfs(0,1,0,'+');
printf("%d\n",ans);
return 0;
}``````