首页 > 其他 > 详细

NOIP2013普及组 T2 表达式求值

时间:2016-03-18 01:49:00      阅读:257      评论:0      收藏:0      [点我收藏+]

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 }
诡异写法

 

NOIP2013普及组 T2 表达式求值

原文:http://www.cnblogs.com/AwesomeOrion/p/5290130.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!