求解小学奥数算法

柯本 2003-04-30 08:54:21
有一小学奥数题:
用2,3,4,5,6及+,-,*,/算出1,每个数字及运算符只能用一次
可以用任意个(),要求得出所有结果(有多个)
如:
5-(3*4/6+2)
4*6/(5+3)-2
-------------------------------------
(最好是C或PASCAL的源程序)
...全文
80 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
柯本 2003-04-30
  • 打赏
  • 举报
回复
ZhangYv说的对,光5!*4!是不够的
ZhangYv 2003-04-30
  • 打赏
  • 举报
回复
其实求结果好做,输出括号是个大麻烦...
BlueSky2008 2003-04-30
  • 打赏
  • 举报
回复
穷举
mathe 2003-04-30
  • 打赏
  • 举报
回复
5!*4!才2880,穷举
ZhangYv 2003-04-30
  • 打赏
  • 举报
回复
有限自动机......faint
柯本 2003-04-30
  • 打赏
  • 举报
回复
能否再改进一下?
mathe 2003-04-30
  • 打赏
  • 举报
回复
好像还有重复的表达式,主要是表达式的等价性很难定义:
比如(5+2-4*6/3)
也可以代表5+2-(4*6)/3,也可以是5+2-4*(6/3)等不同的表达式
mathe 2003-04-30
  • 打赏
  • 举报
回复
27组解(加法和乘法交换意义下相同的解已经淘汰。不过也一些解结果可能是-1
那么只需要将减号左右的数值交换一下就可以了。(比如5/(4+3-6*2) 需要变为5/(6*2-(4+3)).
如果还要重复计数加法和乘法交换率后的解,就有27*4=108组。


5/(4+3-6*2)
(4+3-6*2)/5
4/(5+3-6*2)
(5+3-6*2)/4
3/(6+5-4*2)
(6+5-4*2)/3
3/(5+4-6*2)
(5+4-6*2)/3
(5+4)/(3-6*2)
(3-6*2)/(5+4)
(5+3)/(4-6*2)
(4-6*2)/(5+3)
(4+3)/(5-6*2)
(5-6*2)/(4+3)
4*2/(6+5-3)
4*2/(5+6-3)
4*(5-3)/(6+2)
(5-3*(6+2)/4)
(4-(3+6*2)/5)
(3-(6+5*2)/4)
(3-2*(6+4)/5)
(2-6*4/(5+3))
(6+3-5*4/2)
(6+3-4*5/2)
(5+2-6*4/3)
(5+2-4*6/3)
(5+6/3-4*2)
Total 27 expressions

程序直接使用 http://members.lycos.co.uk/huidu/club/bbsread.php?bbsid=529fcbdc142304ab 下的c++代码,
添加函数:
void tree_iterator::stat_op(int d[])const
{
int i;
int pi,mi;
if(first_child==NULL)return;
tree_iterator *child=first_child;
if(get_prod){
pi=2; // *
mi=3; // /
}else{
pi=0; // +
mi=1; // -
}
d[pi]--;
for(i=0;i<spliter.get_sub_group_count();++i)
{
if(pattern&(1<<i)){
d[pi]++;// *
}else{
d[mi]++;// /
}
child->stat_op(d);
child=child->next_sibling;
}
}

修改main为
int main()
{
int a[5]={2,3,4,5,6};
int count=0;
int d[4];
int cur_scan=0;
{
tree_iterator it(5,a,1);
do
{
d[0]=d[1]=d[2]=d[3]=0;
it.stat_op(d);
if(d[0]!=1||d[1]!=1||d[2]!=1||d[3]!=1)
continue;
if(it.get_value().is_integer()){
int value=it.get_value().get_integer();
if(value==1){
cout<<it.expression()<<endl;
count++;
}
}
}while(it.inc());
}
{
tree_iterator it(5,a,0);
do
{
d[0]=d[1]=d[2]=d[3]=0;
it.stat_op(d);
if(d[0]!=1||d[1]!=1||d[2]!=1||d[3]!=1)
continue;
if(it.get_value().is_integer()){
int value=it.get_value().get_integer();
if(value==1){
cout<<it.expression()<<endl;
count++;
}
}
}while(it.inc());
}
cout << "Total " << count << string(" expressions") << endl;
return 0;
}
FishCrazy 2003-04-30
  • 打赏
  • 举报
回复
那么小学生会怎么做呢?:)

33,008

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧