1139. 电路稳定性(转换成一般表达式,用后缀表达式计算)
2013-01-02 19:53
281 查看
/*1139. 电路稳定性 大意:给出一串电路。求出错概率 思路:把如 (A,B)((C)(D),E)转成 (A+B) * ((C)*(D) + E) 一般表达式 然后转换成后缀表达式 如 (A+B) * ((C)*(D) + E) 转成 pre = AB+CD*E+* 遇到+就计算 1-(1-P(A)) * (1-P(B)) */ #include<iostream> #include<cstdio> #include<string> #include<stack> using namespace std; string expr; double prb[30]; double ans; int pri(char a) { if(a == '(') return -1; return (a == '+') ? 1 : 2; } // 转换成后缀表达式 void convert() { // 转换成一般表达式 //如 (A,B)((C)(D),E)转成 (A+B) * ((C)*(D) + E) string pre = ""; for(int i = 0; i < expr.length(); i ++) { if(expr[i] == ',') pre += '+'; else if(expr[i]==')' && expr[i+1]=='(') pre += ")*"; else pre += expr[i]; } expr = pre; // 转换成后缀表达式 //如 (A+B) * ((C)*(D) + E) 转成 pre = AB+CD*E+* pre = ""; stack<char> sta; for(int i = 0; i < expr.length(); i ++) { if(sta.empty()) { sta.push(expr[i]); continue; } if(expr[i]=='(') { sta.push(expr[i]); continue; } else if(expr[i] == ')') { while( sta.top() != '(' ) { pre += sta.top(); sta.pop(); } sta.pop(); continue; } //如果是字母就直接进入后缀表达式 if(isalpha(expr[i])) pre += expr[i]; //如果是+或* else { //若当前优先级高,则直接进入表达式 *高于+,再次为( if(pri(expr[i]) > pri(sta.top())) sta.push(expr[i]); else { //如果当前优先级低,则把栈中高优先级的一次进入表达式 while(!sta.empty() && pri(expr[i]) <= pri(sta.top())) { pre += sta.top(); sta.pop(); } //然后把当前低的放进栈 sta.push(expr[i]); } } } //把栈中剩余的操作符放进表达式 while(!sta.empty()) { pre += sta.top(); sta.pop(); } expr = pre; } // 后缀表达式的计算 void calc() { stack<double> sta; for(int i = 0; i < expr.length(); i ++) { //元件次序为A B C D E F G... if(isalpha(expr[i])) sta.push(prb[expr[i]-'A']); else { double num1 = sta.top(); sta.pop(); double num2 = sta.top(); sta.pop(); if(expr[i] == '+') sta.push( 1-(1-num1)*(1-num2) ); else sta.push(num1*num2); } } ans = sta.top(); } int main() { int n; while(cin >> n) { cin >> expr; for(int i = 0; i < n; i ++) cin >> prb[i]; convert(); calc(); printf("%.4lf\n",ans); } }
相关文章推荐
- 【综合】中缀表达式转换成后缀表达式后,用后缀表达式计算出结果
- 将一般表达式转换为后缀式,并利用后缀式计算结果
- 中缀表达式转换为后缀表达式,计算后缀表达式
- 暑假集训7.29 一般表达式转换后缀表达式(手写模拟栈....)sdutoj2132
- 数据结构实验之栈二:一般算术表达式转换成后缀式
- Java实现-将普通表达式转换成逆波兰表达式并计算
- SDUTACM 数据结构实验之栈二:一般算术表达式转换成后缀式
- 数据结构实验之栈二:一般算术表达式转换成后缀式
- 数据结构实验之栈与队列二:一般算术表达式转换成后缀式
- C语言::将中缀表达式转换为后缀表达式并计算结果
- 逆波兰式(后缀表达式)的运用-计算四则表达式并用lex,Yacc拓展
- Sicily 1139. 电路稳定性
- Java实现表达式计算(中缀表达式转化为后缀表达式/逆波兰式)
- 数据结构实验之栈二:一般算术表达式转换成后缀式
- 数据结构实验之栈与队列二:一般算术表达式转换成后缀式 sdut-oj
- 数据结构实验之栈二:一般算术表达式转换成后缀式
- 数据结构实验之栈与队列二:一般算术表达式转换成后缀式
- 数据结构实验之栈二:一般算术表达式转换成后缀式
- 数据结构实验之栈二:一般算术表达式转换成后缀式 SDUT
- 数据结构实验之栈二:一般算术表达式转换成后缀式