本文主要是介绍UVA 11291 - Smeech(概率+词法分析),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
UVA 11291 - Smeech
题目链接
题意:给定一个表达式形如e=(p,e1,e2) 该表达式的值为 p∗(e1+e2)+(1−p)∗(e1−e2),求出值
思路:题目是很水,但是处理起来还挺麻烦的,模拟写编译器LEX分析器原理去写了。
代码:
#include <cstdio>
#include <cstring>const int N = 100005;
char str[N];
int now, len, token;
double value;void gettoken() {while (str[now] == ' ') {now++;}if (str[now] == '(') {token = 0; now++;}else if (str[now] == ')') {token = 1; now++;}else if ((str[now] >= '0' && str[now] <= '9') || str[now] == '.' || str[now] == '-') {int flag = 1;if (str[now] == '-') {flag = -1;now++;}value = 0;token = 2;while (now < len && str[now] >= '0' && str[now] <= '9') {value = value * 10 + str[now] - '0';now++;}if (str[now] == '.') {now++;double mu = 10;while (now < len && str[now] >= '0' && str[now] <= '9') {value += (str[now] - '0') / mu;mu *= 10;now++;}}value *= flag;}
}double expr() {gettoken();if (token == 0) {gettoken();double p = value;double x = expr();double y = expr();gettoken();return p * (x + y) + (1 - p) * (x - y);}else return value;
}void init() {now = 0;len = strlen(str);;
}int main() {while (gets(str) && strcmp(str, "()") != 0) {init();printf("%.2lf\n", expr());} return 0;
}
这篇关于UVA 11291 - Smeech(概率+词法分析)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!