5551算24点貌似很强大嘛,必须先算1/5,没有一种运算过程都是整数的方法
(5-1/5)*5
5*(5-1/5)
程序代码:
(5-1/5)*5
5*(5-1/5)
程序代码:
#include <iostream>
#include <algorithm>
#include <string>
#include <stack>
#include <sstream>
using namespace std;
double calc(char op,double& a,double b)
{
switch(op)
{
case '+':return a+=b;
case '-':return a-=b;
case '*':return a*=b;
case '/':return a/=b;
}
return 0;
}
//后缀表达式求值,图省事只支持一位数的
double eval(string poststr)
{
istringstream iss(poststr);
stack<double> S;
for (char ch;iss>>ch;){
if(isdigit(ch)){
S.push(double(ch-'0'));
}
else{
double t=S.top();S.pop();
calc(ch,S.top(),t);
}
}
double res = S.top();S.pop();
return res;
}
char da[] = "5551";
char op[3];
char expr[10];
#define EQ(X,Y) ((X)-(Y)<1e-6 && (Y)-(X)<1e-6)
//枚举所有合法的后缀表达式
void dfs(int dCnt,int oCnt)
{
if(dCnt == 4 && oCnt ==3)
{
if( EQ(eval(expr),24) )
{
puts(expr);
}
}
else
{
//如果操作数比运算符至少多2个,并且还有剩余的运算符,那么可以加一个运算符到后缀表达式结尾
if(dCnt - oCnt >= 2 && oCnt <3)
{
expr[dCnt+oCnt] = op[oCnt];
dfs(dCnt,oCnt+1);
}
//如果还有剩余的操作数,那么可以加一个操作数到后缀表达式结尾
if(dCnt < 4)
{
expr[dCnt+oCnt] = da[dCnt];
dfs(dCnt+1,oCnt);
}
}
}
int main()
{
sort(da,da+4);
do
{
//枚举3个符号
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
for(int k=0;k<4;k++)
{
op[0] = "+-*/"[i];
op[1] = "+-*/"[j];
op[2] = "+-*/"[k];
dfs(0,0);
}
}
}
} while (next_permutation(da,da+4));//枚举操作数的顺序
}










