不同金字塔的数目

Problem Description
小明最近喜欢搭数字积木,
一共有10块积木,每个积木上有一个数字,0~9。
搭积木规则:
每个积木放到其它两个积木的上面,并且一定比下面的两个积木数字小。最后搭成4层的金字塔形,必须用完所有的积木。
下面是两种合格的搭法:
___0
__1_2
_3_4_5
6_7_8_9

___0
__3_1
_7_5_2
9_8_6_4
说明:数字之间的下划线只是为了对齐,没有实际意义请你计算这样的搭法一共有多少种?请填表示总数目的数字。
注意:你提交的应该是一个整数,不要填写任何多余的内容或说明性文字。
Input

Output

输出一个整数

方法一:

暴力解法

#include <iostream>
using namespace std;

int main(){
	int a,b,c,d,e,f,g,h,i,j;
	int count=0;
	
	for(a=0;a<=9;a++){
		for(b=0;b<=9;b++){
			if(a!=b){
				for(c=0;c<=9;c++){
					if(c!=a&&c!=b){
						for(d=0;d<=9;d++){
							if(d!=a&&d!=b&&d!=c){
								for(e=0;e<=9;e++){
									if(e!=a&&e!=b&&e!=c&&e!=d){
										for(f=0;f<=9;f++){
											if(f!=a&&f!=b&&f!=c&&f!=d&&f!=e){
												for(g=0;g<=9;g++){
													if(g!=a&&g!=b&&g!=c&&g!=d&&g!=e&&g!=f){
														for(h=0;h<=9;h++){
															if(h!=a&&h!=b&&h!=c&&h!=d&&h!=e&&h!=f&&h!=g){
																for(i=0;i<=9;i++){
																	if(i!=a&&i!=b&&i!=c&&i!=d&&i!=e&&i!=f&&i!=g&&i!=h){
																		for(j=0;j<=9;j++){
																			if(j!=a&&j!=b&&j!=c&&j!=d&&j!=e&&j!=f&&j!=g&&j!=h&&j!=i){
																				if(b>a&&c>a&&d>b&&e>b&&e>c&&f>c&&g>d&&h>d&&h>e&&i>e&&i>f&&j>f){

																							count++;
																						}
																					}
																				}
																			}
																		}
																	}
																}
															}
														}
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
	

	cout<<count;
	return 0;
}

方法二:

剪枝

#include <iostream>
#include <string.h> 
#include <algorithm>
using namespace std;

int sum=0;
int used[10];
int a[10];

bool judge(int n){
	if(n==2){
		if(a[1]>a[0] && a[2]>a[0])
			return true;
		return false;
	}
	else if(n==5){
		if(a[1]<a[3]&&a[1]<a[4]&&a[2]<a[4]&&a[2]<a[5])
			return true;
		return false;
	}
	else if(n==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]){
			sum++;
			return true;
		} 
		return false;
	}
	else
		return true;
}

void dfs(int n){
	int i;
	for(i=0;i<10;i++){
		if(!used[i]){
			used[i]=1;
			a[n]=i;
			if(!judge(n)){
				used[i]=0;
				continue;
			}
			dfs(n+1);
            used[i]=0;
		}
	}
}

int main(){
	memset(used,0,sizeof(used));
	dfs(0);
	
	cout<<sum<<endl;
	return 0;
} 
答案:768
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值