24点怎么玩
想当年,我六年级在作业盒子的24点口算比赛中拿了
然而,那只是在家里做比赛,根本看不出本人的实力(当然,我没有用c++)。
我早就想做一个解24点的程序(用来刷排名),只可惜24点虽然数据弱爆了,但几乎不能打表,而因为数据弱爆导致算法优化可以忽略不计,所以这题只能用非常难实现的暴力。
现在回想起来,要是我真的用c++做了一个解24点的程序,作业盒子就惨了。
这个程序会找到一种合法方案,包括+-*/
如果没有合法方案,输出"No solution!"
然而我琢磨了一小时,得出(非常丑陋的)结果:
#include<cstdio>
#include<cstdlib>
#include<cstring>
const int
chwhr[5][3]={{0,1,2},{0,1,3},{0,2,6},{0,2,5}},//不要问我这两个奇奇怪怪的数组是干什么的
numwhr[5][4]={{3,4,5,6},{2,4,7,8},{1,5,13,14},{1,11,12,6}};
int num[4];//也不要问我这些变量名怎么这么奇怪
int w[4],treenum[20];
char s[4],treech[20];
bool vis[4],isnum[20];
void print(int step){
if(!isnum[step]){
putchar('(');
print((step<<1)+1);
putchar(treech[step]);
putchar(' ');
print((step<<1)+2);
putchar(')');
}
else printf("%d ",treenum[step]);
return ;
}
double cnt(int step){
// if(step==0) print(0),puts("");
if(isnum[step]) return treenum[step];
char ch=treech[step];
if(ch=='+') return cnt((step<<1)+1)+cnt((step<<1)+2);
if(ch=='-') return cnt((step<<1)+1)-cnt((step<<1)+2);
if(ch=='*') return cnt((step<<1)+1)*cnt((step<<1)+2);
if(ch=='/') return cnt((step<<1)+1)/cnt((step<<1)+2);
}
bool dfsnum(int step){
if(step==4){
for(int i=0;i<4;i++){
memset(isnum,0,20);
for(int j=0;j<3;j++) treech[chwhr[i][j]]=s[j];
for(int j=0;j<4;j++){
treenum[numwhr[i][j]]=w[j];
isnum[numwhr[i][j]]=1;
}
double t=cnt(0);
if(23.99<t&&t<24.01) return 1;
}
return 0;
}
for(int i=0;i<4;i++)
if(!vis[i]){
w[step]=num[i];
vis[i]=1;
if(dfsnum(step+1)) return 1;
vis[i]=0;
}
return 0;
}
bool dfsch(int step){
if(step==3)
return dfsnum(0);
s[step]='+';
if(dfsch(step+1)) return 1;
s[step]='-';
if(dfsch(step+1)) return 1;
s[step]='*';
if(dfsch(step+1)) return 1;
s[step]='/';
if(dfsch(step+1)) return 1;
return 0;
}
int main(){
for(int i=0;i<4;i++) scanf("%d",num+i);
if(dfsch(0)){
print(0);
putchar('\n');
}
else printf("No solution!");
system("pause");
return 0;
}
哪来两个电风扇啊
这个程序不能完全拆括号(不不不,是根本没有拆括号,拆括号要人工执行)。
输入4 4 7 7,输出
(7 * (4 - (4 / 7 )))