HDU 2510 符号三角形(dfs)

来源:互联网 发布:多巴胺检测知乎 编辑:程序博客网 时间:2024/05/16 03:53

Description
符号三角形的 第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
Solution
简单搜索,将三角形倒过来存数组里,0表示-,1表示+,每次枚举dp[1][n]的值,然后往下深搜,开全局变量统计1的数量cnt,当cnt*2==n*(n+1)/2时ans[n]++,注意回溯,但由于搜索会超时而数据范围只有24,所以可以先在本地跑出答案存表里,之后打表过
Code

//打表代码 /*#include<stdio.h>#include<string.h>int dp[25][25],ans[25],cnt;void dfs(int n){    if(n>24)return ;    //枚举该行最后一个符号,由于上一行已经推出,那么只要最后一个符号确定就可以推出该行所有符号    for(int i=0;i<=1;i++)     {        dp[1][n]=i;        cnt+=dp[1][n];        for(int j=2;j<=n;j++)        {            dp[j][n-j+1]=dp[j-1][n-j+1]^dp[j-1][n-j+2];//相同为1,不同为0             cnt+=dp[j][n-j+1];        }        if(cnt*2==n*(n+1)/2)ans[n]++;        dfs(n+1);//深搜         //回溯         cnt-=dp[1][n];        for(int j=2;j<=n;j++)        {            dp[j][n-j+1]=dp[j-1][n-j+1]^dp[j-1][n-j+2];            cnt-=dp[j][n-j+1];        }    }}int main(){    memset(ans,0,sizeof(ans));      memset(dp,0,sizeof(dp));    cnt=0;    dfs(1);    int n;    while(scanf("%d",&n),n)        printf("%d %d\n",n,ans[n]);    return 0;}*/#include<stdio.h>int ans[]={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(scanf("%d",&n),n)        printf("%d %d\n",n,ans[n]);    return 0;}
0 0
原创粉丝点击