POJ 表达式求值
表达式求值.
程序套用的是poj 2252Equation Solver的标程,写的相当漂亮,简洁
所有的表达式求值问题都可以用这种方法解决
算法:ELL(1)-Parser
2106 Boolean Expressions
范式:
Expression := Term { ('+' | '-') Term }
Term := Factor { '*' Factor }
Factor := Number | 'x' | '(' Expression ')'
Number := Digit | Digit Number
Digit := '0' | '1' | ... | '9'
View Code
#include<cstdio> using namespace std; char expr[210]; int p; bool expression(); bool factor() { bool t; if(expr[p]=='(') { p++; t=expression(); p++; } else if(expr[p]=='!') { p++; t=!factor(); } else t=(expr[p++]=='V'?true:false); return t; } bool term() { bool ret=factor(); while(expr[p]=='&') { p++; ret=ret&factor(); } return ret; } bool expression() { bool ret=term(); while(expr[p]=='|') { p++; ret=ret|term(); } return ret; } void Process() { int i,j; for(i=j=0;expr[i]!='\0';i++) if(expr[i]!=' ') expr[j++]=expr[i]; expr[j]='\0'; } int main() { int T=0; while(gets(expr)) { Process(); p=0; //puts(expr); printf("Expression %d: %s\n",++T,expression()?"V":"F"); } return 0; }
POJ 1472 Instant Complexity
与上题稍有不同的是需要用结构体来表示一元多项式
范式:
< Program > ::= "BEGIN" < Statementlist > "END"
< Statementlist > ::= < Statement > | < Statement > < Statementlist >
< Statement > ::= < LOOP-Statement > | < OP-Statement >
< LOOP-Statement > ::= < LOOP-Header > < Statementlist > "END"
< LOOP-Header > ::= "LOOP" < number > | "LOOP n"
< OP-Statement > ::= "OP" < number >
View Code
#include<cstdio> #include<cstring> #include<cstdlib> using namespace std; struct term { int a[11]; }; char s[22]; term Statementlist(); term OP() { term t; char v[22]; int i; for(i=0;i<11;i++) t.a[i]=0; scanf("%s%s",v,s); t.a[0]=atoi(v); return t; } term LOOP() { char v[22]; scanf("%s%s",v,s); int i,k; term t=Statementlist(); if(v[0]=='n') { for(i=9;i>=0;i--) t.a[i+1]=t.a[i]; t.a[0]=0; } else for(k=atoi(v),i=0;i<11;i++) t.a[i]*=k; scanf("%s",s); return t; } term Statement() { if(!strcmp(s,"LOOP")) return LOOP(); return OP(); } term Statementlist() { term t2,t=Statement(); if(!strcmp(s,"END")) return t; t2=Statementlist(); for(int i=0;i<11;i++) t.a[i]+=t2.a[i]; return t; } term Program() { scanf("%s",s); scanf("%s",s); return Statementlist(); } int main() { int T,k,i; term t; scanf("%d",&T); for(k=1;k<=T;k++) { char sign[3]=""; t=Program(); printf("Program #%d\nRuntime = ",k); for(i=10;i>=0;i--) if(t.a[i]) { printf("%s",sign); if(t.a[i]>1||i==0) printf("%d",t.a[i]); if(t.a[i]>1&&i>0) putchar('*'); if(i>1) printf("n^%d",i); if(i==1) putchar('n'); strcpy(sign,"+"); } if(!strcmp(sign,"")) putchar('0'); puts("\n"); } return 0; }