符号三角形
Time Limit: 1000ms Memory Limit: 32768KB
64-bit integer IO format: Java class name:符号三角形的 第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源代码:
#include<iostream>
using namespace std;
#define MAX 25
//打表,不打表会超时,因为回溯算法的时间复杂度是很高的。
int q[MAX][MAX];
int readc[MAX]={0,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 && n){
cout<<n<<" "<<readc[n]<<endl;
}
return 0;
}
打表代码:
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n;
int a[30][30];
int x,y,m;
void dfs(int cnt)
{
if(cnt==n+1)
{
for(int i=n-1;i>0;i--)
for(int j=1;j<=i;j++)
a[i][j]=a[i+1][j]^a[i+1][j+1]; //异或
x=0;y=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=i;j++)
{
if(a[i][j]==1)
x++;
else
y++;
}
if(x==y)
m++;
return;
}
for(int i=0;i<=1;i++)
{
a[n][cnt]=i;
dfs(cnt+1);
}
}
int main()
{
while(scanf("%d",&n)&&n)
{
memset(a,-1,sizeof(a));
m=0;
dfs(1);
printf("%d %d\n",n,m);
}
return 0;
}
来源:https://www.cnblogs.com/q-c-y/p/5483521.html