一道大模拟
代码
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
string st[1010];
int value[26];
int f,o,s,i;
int p[1010],num[1010];
int s1[150];
char s2[150];
int t1=0,t2=0;
char c;
bool check(char ch){
if((ch>='a'&&ch<='z')||(ch>='0'&&ch<='9')||(ch=='+')||(ch=='-')||(ch=='*')
||(ch=='/')||(ch=='(')||(ch==')')||(ch=='='))
return true;
return false;
}
void calcu(){
int x1,x2,x;
char p;
p=s2[t2--];
x2=s1[t1--];
x1=s1[t1--];
switch(p){
case '+' : x=x1+x2; break;
case '-' : x=x1-x2; break;
case '*' : x=x1*x2; break;
case '/' : x=x1/x2; break;
}
s1[++t1]=x;
}
void readStr(){
char b;
s++;
int count=0;
scanf("%c",&b);
while(!check(b)) scanf("%c",&b);
while(check(b)){
st[s]=st[s]+b;
if(b=='d')count++;
if(count>20){
st[s]=st[s].substr(0,3);
break;
}
scanf("%c",&b);
}
}
int result(string t){
char c;
unsigned i=0;
t1=0,t2=0;
int v;
while(i<t.size()){
c=t[i];
if(c=='+'||c=='-'){
while(t2&&s2[t2]!='(') calcu();
s2[++t2]=c;
i++;
}
else if(c=='*'||c=='/'){
while(t2&&(s2[t2]=='*' || s2[t2]=='/')) calcu();
s2[++t2]=c;
i++;
}
else if(c=='('){
s2[++t2]=c;
i++;
}
else if(c==')'){
while(s2[t2]!='(') calcu();
t2--;
i++;
}
else if(c>='a'&&c<='z'){
s1[++t1]=value[c-'a'];
i++;
}else{
v=0;
do{
v=10*v+c-'0';
c=t[++i];
}while(c>='0'&&c<='9'&&i<t.size());
s1[++t1]=v;
}
}
while(t2) calcu();
return s1[t1];
}
int main(){
o=1;
while(o!=0){
readStr();
//cout<<st[s]<<endl;
if(st[s]=="loop") o++;
else if(st[s]=="end") o--;
}
i=2;
f=1;num[1]=1;
while(i<=s){
if(st[i]=="loop"){
f++;
i++;
num[f]=result(st[i]);
i++; p[f]=i;
}
else if(st[i]=="end"){
num[f]--;
if(num[f]==0){
f--;i++;
}else i=p[f];
}
else if(st[i]=="break"){
o=1;
while(o!=0){
i++;
if(st[i]=="loop") o++;
else if(st[i]=="end") o--;
}
num[f]=1;
}else if(st[i]=="continue"){
o=1;
while(o!=0){
i++;
if(st[i]=="loop") o++;
else if(st[i]=="end") o--;
}
}
else if(st[i]=="write"){
i++;
printf("%d
",result(st[i]));
i++;
}
else{
value[st[i][0]-'a']=result(st[i].substr(2,st[i].size()-2));
i++;
}
}
return 0;
}