首页 > 代码库 > UVA - 11291 Smeech (模拟)
UVA - 11291 Smeech (模拟)
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) ande1 and e2 are Smeech expressions. The value represented by a Smeech expression is as follows:- An integer represents itself
- With probability p, (pe1e2) representsx+y where x is the value of e1 and y is the value ofe2; otherwise it represents x-y.
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; }
UVA - 11291 Smeech (模拟)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。