您的位置:首页 > 编程语言 > C语言/C++

2016第七届蓝桥杯C/C++ B组省赛题解 C题 (全排列的学习)

2016-04-08 08:12 513 查看
这个算式中A~I代表1~9的数字,不同的字母代表不同的数字。

B   DEF
A + - + --- = 10
C   GHI


比如:

6+8/3+952/714=10.0 就是一种解法,

5+3/1+972/486=10.0 是另一种解法。

这个算式一共有多少种解法?

利用全排列  (STL)  


#include <algorithm>
next_permutation(<code class="hljs cpp has-numbering">);</code>


点击学习STL

注意精度

#include <cstdio>
#include <algorithm>

using namespace std;

int main(){

int a[11];
for(int i=1;i<=9;i++){
a[i]=i;
}
int flag=0;
do{
if((a[1]+1.0*a[2]/a[3]+1.0*(a[4]*100+a[5]*10+a[6])/(a[7]*100+a[8]*10+a[9]))==10.0){
flag++;
}
}while(next_permutation(a+1,a+10));
printf("%d\n",flag);
return 0;
}

还有一种是用递归 这种要比上面的计算速度快

#include <stdio.h>

int a[10],book[10],coun = 0;

void dfs(int step)
{
if(step == 10)
{
if(a[1]*1.0 + (a[2]*1.0)/a[3] + (a[4]*100 + a[5]*10 + a[6])*(1.0)/(a[7]*100 + a[8]*10 + a[9]) == 10.0)
{
coun ++;
}
return;
}
for(int i = 1; i <= 9; i ++)
{
if(book[i] == 0)
{
a[step] = i;
book[i] = 1;
dfs(step + 1);
book[i] = 0;
}
}
return;
}
int main()
{

dfs(1);
printf("%d\n",coun);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息