sincerit 符号三角形(深搜)

符号三角形

Problem 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

一般的搜索T了
前面输出答案效率还是比较快的到n=19的时候就明显慢了,这里是要去剪枝的但是我不会啊, 虽然靠打表过了

// 超时代码
#include <stdio.h>
#include <cstring>
// 搜索  只要枚举完第n层的,以下n-1层的符号就确定了
int sign[30][30];
int add, sub, sum, n;
void DFS(int c) {
  if (c == n+1) {
    add = 0;sub = 0;
    for (int i = n; i >= 2; i--){
      for (int j = 1; j <= i-1; j++) {
        if (sign[i][j] == sign[i][j+1]) {
          sign[i-1][j] = 1;
          ++add;
        } else {
          sign[i-1][j] = 0;
          ++sub;
        }
      }
    }
    for (int i = 1; i <= n; i++) {
      if (sign[n][i] == 1) ++add;
      else ++sub;
    }
    if (add == sub) ++sum;
    return;
  }
  
  for (int i = 0; i <= 1; i++) {
    sign[n][c] = i;
    DFS(c+1);
    sign[n][c] = 0;
  }
} 
int main() {
  while (scanf("%d", &n), n) {
    sum = 0;
    DFS(1);
    printf("%d %d\n", n, sum);
  }
}

打表代码

#include <stdio.h>
#include <cstring>
int table[28] = {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, table[n]);
  return 0;
}


猜你喜欢

转载自blog.csdn.net/sincerit/article/details/84980606