符号三角形问题
2014-11-12 15:16
405 查看
下图所示的三角形中,有14个“+“和14个“-”。2个同号下面是+,两个异号下面是-。
+ + - + - + +
+ - - - - +
- + + + -
- + + -
- + -
- -
+
在一般情况下,符号三角形的第一行有n个符号。符号三角形问题,要求对于给定的n,计算有多少个不同的符号三角形,使其所含的“+”和“-”相同。
利用回溯法,参考代码如下:
带输出结果的:
+ + - + - + +
+ - - - - +
- + + + -
- + + -
- + -
- -
+
在一般情况下,符号三角形的第一行有n个符号。符号三角形问题,要求对于给定的n,计算有多少个不同的符号三角形,使其所含的“+”和“-”相同。
利用回溯法,参考代码如下:
#include <stdio.h> int sum,count; int half; int **p; int n; void backtrack(int t) { int i,j; if((count>half)||(t*(t-1)/2-count>half)) return; if(t>n) sum++; else { for(i=0;i<2;i++) { p[1][t]=i; count=count+i; for(j=2;j<=t;j++) { p[j][t-j+1]=p[j-1][t-j+1]^p[j-1][t-j+2]; count+=p[j][t-j+1]; } backtrack(t+1); for(j=2;j<=t;j++) count+=p[j][t-j+1]; count-=i; } } } int main() { int i,j; printf("input the number of symbols in the first line:"); scanf("%d",&n); count=0; sum=0; half=(n+1)*n/2; if(half%2==1) { printf("the number is 0"); return 0; } p=new int *[n+1]; for(i=0;i<n+1;i++) p[i]=new int[n+1]; for(i=0;i<n+1;i++) for(j=0;j<n+1;j++) p[i][j]=0; backtrack(1); printf("the result is %d.\n",sum); return 0; }
带输出结果的:
#include <stdio.h> #include <math.h> int n,count=0,half,sum=0; int **a; void backtrack(int t) { if(count>half || (t*(t+1)/2-count>half)) return; int i,j; if(t==n){ sum++; for(i=0;i<n;i++) { for(j=0;j<n-i;j++) { if(a[i][j]) printf("-"); else printf("+"); } printf("\n"); } printf("=====================\n"); } else{ for(i=0;i<2;i++){ a[0][t]=i; count=count+i; for(j=1;j<=t;j++){ a[j][t-j]=a[j-1][t-j]^a[j-1][t-j+1]; count+=a[j][t-j]; } backtrack(t+1); for(j=1;j<=t;j++){ count-=a[j][t-j]; } count=count-i; } } } int main() { int i,j,k; scanf("%d",&n); if((n*(n+1)/2)%2==1) { printf("result is 0.\n"); return 0; } half=n*(n+1)/4; a=new int* ; for(i=0;i<n;i++) a[i]=new int ; for(i=0;i<n;i++) { for(j=0;j<n;j++) a[i][j]=0; } backtrack(0); printf("the result is %d.\n",sum); return 0; }
相关文章推荐
- CodeDom系列二---程序基本结构--符号三角形问题
- 符号三角形问题C++代码
- 符号三角形问题(回溯法)
- 符号三角形问题
- 算法 符号三角形问题
- 回溯法解符号三角形问题
- 符号三角形问题
- 符号三角形问题
- 回溯法求解符号三角形问题
- 符号三角形问题
- 符号三角形问题 回溯法
- 〖編程·C++〗回溯算法:子集树 - 符号三角形问题
- 符号三角形问题-回溯法
- 小白笔记-----------------------符号三角形问题(回溯法---子集树)
- 第5章 回溯法,符号三角形问题
- CodeDom系列二---程序基本结构--符号三角形问题
- 回溯之符号三角形问题
- 符号三角形问题(回溯)
- 符号三角形问题-回溯法
- Python回溯法解符号三角形问题