POJ 3645 解题报告

来源:互联网 发布:c语言程序的基本单位 编辑:程序博客网 时间:2024/05/23 00:42

这道题是简单题。就是递归地解析,求期望。

但是我还是用了很久。。。代码也写得很复杂。看到有神人的清晰代码:

https://github.com/wangyongliang/Algorithm/blob/master/poj/3645/POJ_3645_3644037_AC_0MS_196K.cpp

thestoryofsnow3645Accepted192K0MSC++1732B

/* ID: thestor1 LANG: C++ TASK: poj3645 */#include <iostream>#include <fstream>#include <cmath>#include <cstdio>#include <cstring>#include <limits>#include <string>#include <vector>#include <list>#include <set>#include <map>#include <queue>#include <stack>#include <algorithm>#include <cassert>using namespace std;double eval(char line[]){int len = strlen(line);// printf("line(%d):[%s]\n", len, line);// strip the wightspaces;while (*line == ' '){line++;len--;}while (line[len - 1] == ' '){len--;}double p, x, y;int n1 = 0, num;// if it is an expressionif (line[0] == '('){// delete the matching ')' in the endassert(line[len - 1] == ')');line[len - 1] = '\0';// delete the first '('line++;char *e;e = line;while (*e != ' '){e++;}*e = '\0';sscanf(line, "%lf", &p);// printf("p:%lf\n", p);e++;// if it is another expressionif (e[0] == '('){int unmatched = 1;for (n1 = 1; e[n1] && unmatched; ++n1){if (e[n1] == '('){unmatched++;}else if (e[n1] == ')'){unmatched--;}}assert(unmatched == 0 &&  e[n1 - 1] == ')');assert(e[n1] == ' ');e[n1] = '\0';x = eval(e);}else{// it is an integer herewhile (e[n1] != ' '){++n1;}e[n1] = '\0';sscanf(e, "%d", &num);x = num;}// e2 follows e1y = eval(e + n1 + 1);return p * (x + y) + (1 - p) * (x - y);}else{sscanf(line, "%d", &num);x = num;return x;}}int main(){// 7// (.5 3 9)char line[1000];double p;int e1, e2;while (gets(line) && strcmp(line, "()") != 0){printf("%.2lf\n", eval(line));}return 0;  }


0 0
原创粉丝点击