幸运三角形

时间限制:65535 KB
难度:3
 
描述

        话说有这么一个图形,只有两种符号组成(‘+’或者‘-’),图形的最上层有n个符号,往下个数依次减一,形成倒置的金字塔形状,除第一层外(第一层为所有可能情况),每层形状都由上层决定,相邻的符号相同,则下层的符号为‘+’,反之,为‘-’;如下图所示(n = 3 时的两种情况):

                                           NYOJ-491 幸运三角形

如果图中的两种符号个数相同,那这个三角形就是幸运三角形,如上图中的图(2).

 
输入
有多组测试数据(少于20组)。
每行含一个整数n(0<n<20)。
输出
输出相应的幸运三角形个数。
样例输入
3
4
样例输出
4
6


代码一:  TLE 
 1 #include <cstdio>
 2 #include <iostream>
 3 
 4 using namespace std;
 5 int a[25];
 6 int n, cnt;
 7 
 8 bool judge()
 9 {
10     int t0, t1;
11     t0 = t1 = 0;
12     for(int end = n; end >= 1; --end)
13     {
14         for(int i = 1; i <= end; ++i)
15         {
16             if(a[i] == 1)
17                 ++t1;
18             else
19                 ++t0;
20             if(t1 > ((n+1)*n>>1) || t1 > ((n+1)*n>>1))  //剪枝 
21                 return false;
22             if(i > 1)
23             {
24                 if(a[i] == a[i-1])
25                     a[i-1] = 1;
26                 else
27                     a[i-1] = 0;
28             }
29         }
30     }
31     if(t0 == t1)
32         return true;
33     return false;
34 }
35 
36 void DFS(int cur)
37 {
38     if(cur > n)
39     {
40         if(judge())
41             ++cnt;
42         return;
43     }
44     a[cur] = 1;
45     DFS(cur+1);
46     a[cur] = 0;
47     DFS(cur+1);
48 }
49 
50 int main()
51 {
52     while(scanf("%d", &n))
53     {
54         if(((n+1)*n>>1) & 1)
55         {
56             printf("0\n");
57             continue;
58         }
59         cnt = 0;
60         DFS(1);
61         printf("%d\n", cnt);
62     }
63     return 0;
64 }
View Code

相关文章:

  • 2022-12-23
  • 2022-01-16
  • 2021-10-06
  • 2022-02-12
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-02
  • 2021-05-29
  • 2021-05-29
  • 2022-01-23
  • 2021-12-31
  • 2021-11-29
相关资源
相似解决方案