您的位置:首页 > 其它

符号三角形问题

2014-11-12 15:16 405 查看
     下图所示的三角形中,有14个“+“和14个“-”。2个同号下面是+,两个异号下面是-。

+ + - + - + +
+ - - - - +
- + + + -
- + + -
- + -
- -
+

    在一般情况下,符号三角形的第一行有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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: