HDU—2510 符号三角形 (深搜打表)

符号三角形的 第1行有n个由“+”和”-“组成的符号 ,以后每行符号比上行少1个,2个同号下面是”+“,2个异 号下面是”-“ 。计算有多少个不同的符号三角形,使其所含”+“ 和”-“ 的个数相同 。 n=7时的1个符号三角形如下:
+ + - + - + +
+ - - - - +
- + + + -
- + + -
- + -
- -
+

Input

每行1个正整数n <=24,n=0退出.

Output

n和符号三角形的个数.

Sample Input

15
16
19
20
0

Sample Output

15 1896
16 5160
19 32757
20 59984

这道题一共就24个数据,所以我们完全可以暴力搜索打印所以的可能,存到数组里,直接用就行

//打表
#include<iostream>
#include<cstring>
using namespace std;
int ans[30];
int m[30][30];
int count;
void dfs(int n){
	if(n>24)
	    return ;
	for(int i=0;i<=1;i++){
		m[1][n]=i;//暴力第一行 
		count+=i; //记录1的个数
		for(int j=2;j<=n;j++){//把这一种n遍历完 
			if(m[j-1][n-j+1]==m[j-1][n-j+2])
			    m[j][n-j+1]=1;
			else
			    m[j][n-j+1]=0;
			count+=m[j][n-j+1];
		} 
		if(count*2==n*(n+1)/2)//右边是那个直角三角形的元素个数 
		    ans[n]++; 
		dfs(n+1);//下一个 
		count-=i;
		for(int j=2;j<=n;j++){//取消标记 
			if(m[j-1][n-j+1]==m[j-1][n-j+2])
			    m[j][n-j+1]=1;
			else
			    m[j][n-j+1]=0;
			count-=m[j][n-j+1];//把刚才加上的减掉 
		} 
	}
}
int main(){
	int n;
	memset(ans,0,sizeof(ans));
	count=0;
	dfs(1);
	for(int i=1;i<=24;i++){
		cout<<"ans["<<i<<"] = "<<ans[i]<<endl;
	} 
	while(~scanf("%d",&n)&&n){
		printf("%d\n",ans[n]);
    }
    return 0;
} 
#include<iostream>
using namespace std;
int ans[25]={0,0,4,6,0,0,12,40,0,0,171,410,0,0,1896,5160,0,0,32757,59984,0,0,431095,822229};
int main(){
	int n;
	while(cin>>n){
		if(!n)
		    break;
		cout<<n<<" "<<ans[n-1]<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/red_red_red/article/details/88978618