2016第七届蓝桥杯C/C++ B组省赛题解 C题 (全排列的学习)
2016-04-08 08:12
513 查看
这个算式中A~I代表1~9的数字,不同的字母代表不同的数字。
比如:
6+8/3+952/714=10.0 就是一种解法,
5+3/1+972/486=10.0 是另一种解法。
这个算式一共有多少种解法?
利用全排列 (STL)
点击学习STL
注意精度
还有一种是用递归 这种要比上面的计算速度快
#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;
}
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;
}
相关文章推荐
- 直接拿来用!最火的Android开源项目(一)
- <string> 与<string.h>、<cstring>的区别
- C++primer 练习12.6
- C++设计模式<四>:策略模式(Strategy)
- C++实现栈
- C语言 详解多级指针与指针类型的关系
- 好久没写过博客,写一道今天的笔试题
- 2016第七届蓝桥杯C/C++ B组省赛题解 A题
- 关于C语言的问卷调查!!!!!!!!!!
- C语言问卷调查
- 《高质量C++/C编程指南》读书笔记二
- MySQL Connector/C++ Mac Xcode
- 关于Bjarne Stroustrups教授与C++
- 关于c++的命名空间
- CFILE文件类CFile::Read
- 一个关于C语言单链表的简单应用程序
- C++中常量指针,指针常量(const 和*)的使用方法和理解方法
- C++混合编程之idlcpp教程Python篇(5)
- 结构体练手
- C++实验3-本月有几天?