OJ地址:洛谷P1981 CODEVS 3292

 

正常写法是用栈

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cmath>
 4 #include<stack>
 5 #include<cstring>
 6 #include<cstdio>
 7 using namespace std;
 8 char c[20000000];
 9 
10 stack<long long>num;//
11 stack<char>sy;//符号
12 void mth(){//运算
13     int a,b;
14     char ch;
15     b=num.top();
16     num.pop();
17     a=num.top();
18     num.pop();
19     ch=sy.top();
20     sy.pop();
21     switch(ch){
22         case '+': num.push((a+b)%10000);break;
23         case '*': num.push((a*b)%10000);break;
24     }
25     return;
26 }
27 int cmp(int ch){//优先级判断,没有严谨验证过,初步测试没有问题
28     if(sy.empty() || sy.top()=='(')return 0;
29     if(ch=='+' || ch=='-')return 1;
30     if(ch=='*' && sy.top()=='*')return 1;
31     return 0;
32 
33 int main(){
34     gets(c);
35     int len=strlen(c);
36     c[len]=')';
37     sy.push('(');
38     int i;
39     
40    if(c[0]<'0'||c[0]>'9'){
41         num.push(0);
42     }
43     
44     
45     for(i=0;i<=len;i++){
46         if(c[i]=='('){
47             sy.push('(');
48             continue;
49         }
50         if(c[i]>='0' && c[i]<='9')
51         {
52             long long x=0;
53             while(c[i]>='0' && c[i]<='9'){
54                 x=x*10+c[i]-'0';
55                 i++;
56             }
57             i--;
58             num.push(x);
59             continue;
60         }
61         if(c[i]==')'){
62             while(sy.top()!='(')mth();
63             sy.pop();
64             continue;
65         }
66         
67         
68         
69         while(cmp(c[i]))mth();
70         sy.push(c[i]);
71     }
72     while(!sy.empty())mth();
73     cout<<num.top()%10000; 
74 //    printf("%d ",num.top()%10000);
75     return 0;
76 }
正常写法

相关文章: