小明最近喜欢搭数字积木,
一共有10块积木,每个积木上有一个数字,0~9。
搭积木规则:
每个积木放到其它两个积木的上面,并且一定比下面的两个积木数字小。
最后搭成4层的金字塔形,必须用完所有的积木。
下面是两种合格的搭法:
0
1 2
3 4 5
6 7 8 9
0
3 1
7 5 2
9 8 6 4
请你计算这样的搭法一共有多少种?
请填表示总数目的数字。
注意:你提交的应该是一个整数,不要填写任何多余的内容或说明性文字。
#include <iostream>
using namespace std;
int a[10];
int ans=0;
bool vis[10];
bool test(int step){//对不合适的进行剪枝
if (step==2)
{
if (a[0]<a[1] && a[0]<a[2])//满足第一层
{
return 1;
}
return 0;
}else if(step==5)
{
if (a[1]<a[3] && a[1]<a[4] && a[2]<a[4] && a[2]<a[5])//满足第二层
{
return 1;
}
return 0;
}else if(step==9)
{
if (a[3]<a[6] && a[3]<a[7] && a[4]<a[7] && a[4]<a[8] && a[5]<a[8] && a[5]<a[9])//满足第三层
{
ans++;//如果满足,可行解+1
return 1;
}
return 0;
}
}
void dfs(int step){
for (int i = 0; i < 10; i++)
{
if (!vis[i])
{
vis[i]=1;
a[step]=i;
if (!test(step))//如果不符合则重新赋值,并跳出本次循环
{
vis[i]=0;
continue;
}
dfs(step+1);
vis[i]=0;
}
}
return;
}
int main(){
dfs(0);
cout<<ans<<endl;
return 0;
}
不剪枝:
#include <iostream>
using namespace std;
int a[10];
int ans=0;
bool vis[10];
bool test(int step){
if (a[0]<a[1] && a[0]<a[2] &&
a[1]<a[3] && a[1]<a[4] && a[2]<a[4] && a[2]<a[5] &&
a[3]<a[6] && a[3]<a[7] && a[4]<a[7] && a[4]<a[8] && a[5]<a[8] && a[5]<a[9])//满足三层
{
return 1;
}else
{
return 0;
}
}
void dfs(int step){
if (step==10)
{
if (test(step))
{
ans++;
}
return;
}
for (int i = 0; i < 10; i++)
{
if (!vis[i])
{
vis[i]=1;
a[step]=i;
dfs(step+1);
vis[i]=0;
}
}
return;
}
int main(){
dfs(0);
cout<<ans<<endl;
return 0;
}