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(概率+词法分析),布布扣,bubuko.com
时间: 2024-12-09 12:11:21