题目:
http://acm.hdu.edu.cn/showproblem.php?pid=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
思路:
n比较小,直接暴力打表,计算出所有结果,然后直接输出结果
打表代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 110;
int work(int n)
{
int res = 0;
char s[N][N];
memset(s, 0, sizeof s);
for(int i = 0; i < (1<<n); i++) //第一行的状态数为(1<<n)个,通过位运算枚举第一行的所有情况,然后就可以推出其他行,统计'+'和'-'的个数
{
int num1 = 0, num2 = 0;
for(int j = 0; j < n; j++)
if((i>>j)&1) s[1][n-j] = '+', num1++;
else s[1][n-j] = '-', num2++;
for(int j = 2; j <= n; j++)
{
for(int k = 1; k <= n-j+1; k++)
if(s[j-1][k] == s[j-1][k+1]) s[j][k] = '+', num1++;
else s[j][k] = '-', num2++;
}
if(num1 == num2) res++;
}
return res;
}
int main()
{
for(int i = 1; i <= 24; i++) printf("%d,", work(i));
return 0;
}
提交代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
int res[] = {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 n;
while(scanf("%d", &n), n) printf("%d %d\n", n, res[n]);
return 0;
}