您的位置:首页 > 其它

hdu2510 符号三角形(dfs+打表) 解题报告

2015-07-30 22:44 281 查看
Problem Description

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

+ + - + - + +

+ - - - - +

- + + + -

- + + -

- + -

- -

+

Input

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

Output

n和符号三角形的个数.

Sample Input

15
16
<span style="font-family: 'Courier New', Courier, monospace; font-size: 14px; white-space: pre-wrap; background-color: rgb(240, 240, 240);">19</span>
200


Sample Output

15 1896
16 5160
19 32757
20 59984


暴力思路:题目要求下一行由上一行两个得,所以,知道下一个和上一个得左边,也可以得到上一行得右边。

代码如下:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <vector>
#include <map>
using namespace std;
const int maxn=30;
int f[maxn][maxn];
int res[maxn];
void dfs(int t,int s)//层数,和
{
int i,j,ans;
for(i=0; i<2; i++)//枚举第一个数
{
f[t][0]=i;
ans=i;
for(j=1; j<t; j++)
{
f[t][j]=f[t][j-1]^f[t-1][j-1];//因为题目要求
ans+=f[t][j];
}
if((1+t)*t/2==(ans+s)*2)res[t]++;
if(t==24)continue;
dfs(t+1,s+ans);
}
}
void init()
{
memset(f,0,sizeof(f));
memset(res,0,sizeof(res));
dfs(1,0);
}
int main()
{
init();
for(int i=1; i<=24; i++)
{
if(i==1)printf("%d",res[i]);
else if(i==24)printf(",%d\n",res[i]);
else printf(",%d",res[i]);
}
}
//打表得0,0,4,6,0,0,12,40,0,0,171,410,0,0,1896,5160,0,0,32757,59984,0,0,431095,822229

提交代码:

#include <cstdio>
using namespace std;

const int maxn=30;
int ans[maxn]={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(scanf("%d",&n)!=EOF&&n!=0)
{
printf("%d %d\n",n,ans[n-1]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: