OJ解题报告 2990:符号三角形

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

n=7时的1个符号三角形如下:
+ + - + - + +
+ - - - - +
- + + + -
- + + -
- + -
- -
+
输入
每行1个正整数n<=24,n=0退出.
输出
n和符号三角形的个数.
样例输入

15
16
19
20
0

样例输出

15 1896
16 5160
19 32757
20 59984

简直纯纯一打表、、随便搜搜就行了、但出于对Noi题库的尊重,还是好好写一下。首先想到搜索,直接搜出所有情况(224并没有多大【滑稽】)。然后考虑验证。如果单纯模拟的话,tle无疑。所以考虑增加状压+记忆化,但空间又不够,于是加一个判断,爆空间则不记忆,否则记忆。一同乱搞凭借着测评机的给力终于AC。

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int num = 1;
int s[3][30];
int dp[8000050];

int n;

int judge(int k) {
    //cout << k << endl;
    if (k < 8000050 && dp[k] != -1) return dp[k];
    if (k == 2) return 0;
    if (k == 3) return 1;
    int pst = k, ans = 0, i = 1;
    while(k != 1) {
        if (k&1) ans++;
        s[1][i++] = k&1;
        //cout << s[1][i-1] << " ";
        k>>=1;
    }
    --i;
    for (int j = 1; j <= i/2; j++) {
        swap(s[1][j],s[1][i-j+1]);
    }
    for (int j = 1; j <= i; j++) {
        //cout << s[1][j] << " ";
    }
    //cout << " ";
    for (int j = 1; j <= i-1; j++) {
        s[2][j] = (s[1][j]==s[1][j+1]);
        //cout << s[2][j] << " ";
    }
    //puts("");
    for (int j = 1; j <= i-1; j++) {
        k<<=1;
        if (s[2][j]) k++;
    }
    if (pst > 8000050) return ans+judge(k);
    return dp[pst] = ans+judge(k);
}

int dfs(int i = 1) {
    if (i == n+1) {
        //cout<<num <<" " << judge(num) << endl;
        return judge(num) == n*(n+1)/4?1:0;
    }
    int ans = 0;
    int pst = num<<1;
    num <<= 1;
    ans += dfs(i+1);
    num = pst+1;
    ans += dfs(i+1);
    return ans;
}

int main() {
    memset(dp,-1,sizeof dp);
    memset(s,0,sizeof s);
    //cout << judge(21) << endl;
    while (1) {
        scanf("%d", &n);
        num = 1;
        if (n==0) break;
        if (n*(n+1)/2%2 != 0) {
            cout << n << " " << 0 << endl;
            continue;
        }
        printf("%d %d
", n, dfs(1));
    }
    return 0;
}
原文地址:https://www.cnblogs.com/ljt12138/p/6684377.html