题目:
注:蓝桥杯2016年省赛C++A组第6题
请填写表示方案数目的整数。
题解:
由题可知这是一道全排列问题,因此我们可以使用c++的next_permutation函数对于1-13的数字进行全排列即可,并每次排列判断是否满足题意。
注意:你提交的应该是一个整数,不要填写任何多余的内容或说明性文字。
代码:
方法1(c++):
cpp
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
int ans = 0;
int a[13]={1,2,3,4,5,6,7,8,9,10,11,12,13};//由于本身就是一种排列方式,所以先判断,所以使用do-while循环
do{
if(a[0]+a[1]==a[2]&&a[3]-a[4]==a[5]&&a[6]*a[7]==a[8]&&a[9]%a[10]==0 &&a[9]/a[10]==a[11])
ans++;
}
while(next_permutation(a,a+13));//开始为从小到大排列,因此此时可以输出全排列
cout<<ans<<endl;
return 0;
}
方法2(c++):
cpp
#include<iostream>
using namespace std;
int a[14],vis[14],cnt = 0;
void dfs( int x ){
if( x == 12 ){
cnt++;
return ;
}
if( x == 2 ){
a[2] = a[1] + a[0] ;
if( a[2] <= 13 && a[2] >=1 && !vis[ a[2] ] ){
vis[ a[2] ] = 1;
dfs( x + 1 );
vis[ a[2] ] = 0;
}
else return ;
}
else if( x == 5 ){
a[5] = a[3] - a[4];
if( a[5] <= 13 && a[5] >=1 && !vis[ a[5] ] ){
vis[ a[5] ] = 1;
dfs( x + 1 );
vis[ a[5] ] = 0;
}
else return ;
}
else if( x == 8 ){
a[8] = a[6] * a[7];
if( a[8] <= 13 && a[8] >=1 && !vis[ a[8] ] ){
vis[ a[8] ] = 1;
dfs( x + 1 );
vis[ a[8] ] = 0;
}
else return ;
}
else if( x == 11 ){
if( a[9] % a[10]== 0 )
a[11] = a[9] /a[10];
else return ;
if( a[11] <= 13 && a[11] >=1 && !vis[ a[11] ] ){
vis[ a[11] ] = 1;
dfs( x + 1 );
vis[ a[11] ] = 0;
}
else return ;
}
else {
for( int i= 1;i<=13;i++){
if( !vis[i] ){
vis[i] = 1;
a[x] = i;
dfs( x + 1 );
vis[i] = 0;
}
}
}
}
int main(void){
dfs( 0 );
printf("%d\n",cnt);
return 0;
}
方法3(python):
python
summary = [x for x in range(1,14)]
summit = 0
for item in summary:
summary_1 = summary.copy()
summary_1.remove(item)
for item_1 in summary_1:
summary_2 = summary_1.copy()
summary_2.remove(item_1)
for item_2 in summary_2:
summary_3 = summary_2.copy()
summary_3.remove(item_2)
for item_3 in summary_3:
summary_4 = summary_3.copy()
summary_4.remove(item_3)
for item_4 in summary_4:
summary_5 = summary_4.copy()
summary_5.remove(item_4)
for item_5 in summary_5:
summary_6 = summary_5.copy()
summary_6.remove(item_5)
for item_6 in summary_6:
summary_7 = summary_6.copy()
summary_7.remove(item_6)
for item_7 in summary_7:
summary_8 = summary_7.copy()
summary_8.remove(item_7)
a = item + item_1
b = item_2 - item_3
c = item_4 * item_5
d = item_6 / item_7
if a in summary_8 and b in summary_8 and c in summary_8 and d in summary_8:
summit += 1
print(summit)