1. 程式人生 > >NOIP2013普及組 T2 表示式求值

NOIP2013普及組 T2 表示式求值

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 }
正常寫法

然而還有超詭異的解法

 1 /*NOIP2013普及組t2 洛谷P1981 表示式求值*/
 2 /**/
 3 #include<algorithm>
 4 #include<iostream>
 5 #include<cstring>
 6 #include<cstdio>
 7 #include<cmath>
 8 using namespace std;
 9 char last;
10 char c;
11 int x=0;
12 int a=0,b=1;
13 int sum=0;
14 int main(){
15     int i,j;
16     bool flag=1;
17     do{
18         if(cin>>c);
19         else{
20             flag=0;
21             c='+';//相當於在整個串最後補個+號,以完成全部運算
22         }
23         if(c>='0' && c<='9')x=x*10+c-'0';
24         else{
25             a=x;
26             x=0;
27         }
28         if(c=='*'){
29             last=1;
30             b=(a*b)%10000;
31         }
32         if(c=='+'){
33             if(last){
34                 a=(a*b)%10000;
35                 sum=(sum+a)%10000;
36                 b=1;
37                 last=0;
38             }
39             else sum+=a;
40         }
41         
42     }while(flag==1);
43     printf("%d",sum%10000);
44     return 0;
45 }
詭異寫法