24点游戏(Ⅰ)
来源:互联网 发布:千牛mac版什么时候出 编辑:程序博客网 时间:2024/06/07 17:23
问题 M: 24点游戏(Ⅰ)
时间限制: 1 Sec 内存限制: 128 MB
提交: 748 解决: 183
[提交][状态][讨论版]
题目描述
24点游戏的玩法是这样的:任取一幅牌中的 4张牌(不含大小王),每张牌上有数字(其中A 代表1,J 代表11,Q 代表 12,K代表13),你可以利用数学中的加、减、乘、除以及括号想办法得到24,每张牌只能用一次。例如有四张6,那么6+6+6+6=24,也可以6*6-6-6=24。但是有些牌是无法得到24的,比如两张 A 和两张2。
读入表达式树的先序遍历字符串, 这里的表达式树是来自24点游戏的真实场景,也就是对应四个数字(值在1到13之间)组成的表达式,问该表达式树能不能得到24?
输入
输入由多组测试数据组成。
每组数据包含一行字符串,即24点游戏的表达式树的先序遍历序列。
输出
对于每组数据,输出一行。如果不能得到24,输出“NO”。如果能得到24,按样例输出。
样例输入
+ + + 6 # # 6 # # 6 # # 6 # #
- - * 6 # # 6 # # 6 # # 6 # #
* * 1 # # 2 # # * 1 # # 2 # #
样例输出
(((6+6)+6)+6)=24
(((6*6)-6)-6)=24
NO
#include<stdio.h>#include<string.h>#include<stdlib.h>#include<math.h>typedef struct binode{ char data[4]; int h; int depth; struct binode *lchild,*rchild;}binode,*bitree;char d[100][100];int q=0,num1,sum;void creatbitree(bitree &T,int y,int num){ if(d[q][0]=='#') {T=NULL;q++;} else { T=new binode; if(y==1) T->h=1; else T->h=0; T->depth=++num; strcpy(T->data,d[q++]); creatbitree(T->lchild,1,T->depth); creatbitree(T->rchild,0,T->depth); }}void travel(bitree T){ int i; if(T!=NULL) { if(T->data[0]=='+'||T->data[0]=='-'||T->data[0]=='*'||T->data[0]=='/') { printf("("); travel(T->lchild); printf("%s",T->data); travel(T->rchild); printf(")"); } else printf("%s",T->data); }}float calculate(bitree T){ if(T!=NULL) { if(T->data[0]=='+'||T->data[0]=='-'||T->data[0]=='*'||T->data[0]=='/') { switch(T->data[0]) { case'+':return(calculate(T->lchild)+calculate(T->rchild));break; case'-':return(calculate(T->lchild)-calculate(T->rchild));break; case'*':return(calculate(T->lchild)*calculate(T->rchild));break; case'/':if(calculate(T->rchild)-0>=0.00001) {return(calculate(T->lchild)/calculate(T->rchild));break;} else break; } } else { char a[1000]; strcpy(a,T->data); //puts(a); float sum1=0; int i; for(i=0;a[i]!='\0';i++) { sum1=sum1*10+a[i]-'0'; } //printf("sum=%f\n",sum1); return sum1; } }}int main(){ char a[500]; bitree T; while(gets(a)!=NULL) { int i,j=0,k=0; q=0; sum=0; for(i=0;a[i]!='\0';i++) { if(a[i]!=' ') d[j][k++]=a[i]; else { d[j][k++]='\0'; //puts(d[j]); k=0; j++; } } d[j++][k++]='\0'; creatbitree(T,2,0); if(fabs(calculate(T)-24)<0.00001) { travel(T); printf("=%d",(int)calculate(T)); } else printf("NO"); printf("\n"); }}
阅读全文
0 0
- 24点游戏(Ⅰ)
- 24点游戏代码
- 24点游戏
- 24点扑克牌游戏
- 24点游戏
- 24点游戏
- 《24点游戏》
- 24点游戏
- 24点游戏
- 24点游戏
- 24点游戏
- 24点游戏
- 24点游戏
- 24点游戏
- 24点游戏源码
- 24点游戏
- 24点游戏-hero
- 24点游戏
- 表达式树的值
- Popupwindow属性点击事件
- Overtime temporary Pseudocode. will delete.
- 更新Android SDK
- Xcode下载
- 24点游戏(Ⅰ)
- Java数组
- 52 WebGL不使用任何方法绘制矩形
- IntelliJ中的main函数和System.out.println()快捷输入方式
- leetcode 515. Find Largest Value in Each Tree Row
- [Algorithm]Quick Select问题
- node 任务热加载
- 素数距离OJ
- 表达式树的创建与输出