题目描述
针对原文的代码改进
#include <iostream>
#include <cstring>
using namespace std;
const int N = 101;
int n ,sum ,half , count;
int p[N][N];
void dfs(int t)
{
//约束函数,判断"+"和"-"是否都超过了一半
if(count > half || t*(t - 1) / 2 - count > half) return;
if(t > n)
{
sum++;
for(int i = 1; i <= n; i++)
{
for (int k = 0; k < i; k++) cout << " ";
for(int j = 1; j <= n - i + 1; j++)
cout << p[i][j] << " ";
cout << endl;
}
cout << endl;
}
for(int i = 0;i <= 1;i++)
{
p[1][t] = i;
count += i;
for(int j = 2;j <= t;j++)
{
p[j][t-j+1] = p[j-1][t-j+1] == p[j-1][t-j+2] ? 1 : 0 ;
count += p[j][t-j+1];
}
dfs(t + 1);
for(int j = 2;j <= t;j++)
count -= p[j][t - j + 1];
count -= i;
p[1][t] = 0;
}
}
int main()
{
cin >> n;
half = n*(n+1) >> 1;
if(half % 2 == 0) half >>= 1,dfs(1);
printf("SUM: %d",sum);
return 0;
}
ok,结束