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

来源:互联网 发布:世界卫生组织数据库 编辑:程序博客网 时间:2024/05/20 03:41

这个算式中A~I代表1~9的数字,不同的字母代表不同的数字。

    B   DEFA + - + --- = 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;}


0 0
原创粉丝点击