Description
Problem B: Smeech
Professor Octastichs has invented a new programming language, Smeech. An expression in Smeech may be a positive or negative integer, or may be of the form
(pe1e2) where p is a real number between 0 and 1 (inclusive) and
e1 and e2 are Smeech expressions. The value represented by a Smeech expression is as follows:
- An integer represents itself
- With probability p, (pe1e2) represents
x+y where x is the value of e1 and y is the value of
e2; otherwise it represents x-y.
Given a Smeech expression, what is its expected value?
Input consists of several Smeech expressions, one per line, followed by a line containing (). For each expression, output its expected value to two decimal places.
Sample Input
7 (.5 3 9) ()
Output for Sample Input
7.00 3.00 题意:给出个表达式(p,e1,e2)表示(e1+e2)*p+(e1-e2)*(1-p)的结果,求最后的值 思路:递归的处理整个式子,注意细节小数的时候的判断#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 10005; char str[maxn]; int cur, len; double cal() { double op = 1; while (!(str[cur]=='(' || (str[cur]>='0'&&str[cur]<='9') || str[cur]=='-') && cur < len) cur++; if (str[cur] == '-') { cur++; op = -1; } if (str[cur] == '(') { cur++; double w = 0.1, p = 0; if (str[cur] == '.' || str[cur+1] == '.') { if (str[cur+1] == '.') cur++; for (int i = cur+1; str[i] >= '0' && str[i] <= '9' && str[i]; i++, cur = i) { p = p + (str[i] - '0') * w; w *= 0.1; } } else p = str[cur++] - '0'; double a, b; a = cal(); b = cal(); return (a + b) * p + (a - b) * (1 - p); } else { double p = 0; for (int i = cur; str[i] >= '0' && str[i] <= '9' && str[i]; i++, cur = i) p = p * 10 + str[i] - '0'; return op * p; } } int main() { double p, a, b; while (gets(str) && strcmp(str, "()")) { len = strlen(str); cur = 0; printf("%.2lf\n", cal()); } return 0; }
时间: 2024-10-27 08:25:52