西南民大oj 1762 我的式子不可能那么难写 【波兰式】

1+2
3+(5-6/(1+2)+10)*8

3
107

←_←

思路：很久以前西南民大比赛做过的题,其实就是给你一个表达式让你求值,我们可以先将它变成波兰式,然后波兰式求值就简单多了

 1 #include <cstdio>
2 #include <iostream>
3 #include <algorithm>
4 #include <string.h>
5 #include <stack>
6 #define maxn 100009
7 using namespace std;
8 stack<char>q;
9 stack<long long>p;
10 long long priorit[1000],ans[maxn],h;
11 bool opp[maxn];
12 char ch[maxn];
13 int main()
14 {
15     priorit[(int)'+']=priorit[(int)'-']=1;
16     priorit[(int)'*']=priorit[(int)'/']=2;
17     priorit[(int)'(']=0;
18     while(gets(ch+1)!=NULL)
19     {
20         while(!q.empty())q.pop();
21         while(!p.empty())p.pop();
22         h=0;
23         memset(ans,0,sizeof(ans));
24         memset(opp,0,sizeof(opp));
25         long long len=strlen(ch+1),idx=1,j=1;
26         for(int i=1;i<=len;i++)
27         {
28             if(ch[i]!=' ')ch[j++]=ch[i];
29         }
30         len=j-1;
31         while(idx<=len)
32         {
33             long long num=0,flag=0;
34             while(ch[idx]>='0'&&ch[idx]<='9'&&idx<=len)
35             {
36                 num=num*10+ch[idx++]-'0';
37                 flag=1;
38             }
39             if(flag==0)
40             {
41                 if(ch[idx]=='(')q.push('(');
42                 else if(ch[idx]==')')
43                 {
44                     while(!q.empty()&&q.top()!='(')
45                     {
46                         ans[++h]=-(long long)q.top();
47                         opp[h]=1;
48                         q.pop();
49                     }
50                     q.pop();
51                 }
52                 else
53                 {
54                     while(!q.empty()&&priorit[(long long)q.top()]>=priorit[(int)ch[idx]])
55                     {
56                         ans[++h]=-(int)q.top();
57                         opp[h]=1;
58                         q.pop();
59                     }
60                     q.push(ch[idx]);
61                 }
62             }
63             else
64             {
65                 ans[++h]=num;
66             }
67             if(flag==0)idx++;
68         }
69         while(!q.empty())
70         {
71             ans[++h]=-(long long)q.top();
72             opp[h]=1;
73             q.pop();
74         }
75         for(int i=1;i<=h;i++)
76         {
77            // printf("%I64d ",ans[i]);
78             if(opp[i]==0)p.push(ans[i]);
79             else
80             {
81                 long long u=p.top();
82                 p.pop();
83                 long long v=p.top();
84                 p.pop();
85                 if(ans[i]==-(int)'-')p.push(v-u);
86                 if(ans[i]==-(int)'+')p.push(u+v);
87                 if(ans[i]==-(int)'*')p.push(u*v);
88                 if(ans[i]==-(int)'/')p.push(v/u);
89             }
90         }
91         if(!p.empty())printf("%I64d\n",p.top());
92         else printf("0\n");
93     }
94 }

posted @ 2015-03-29 15:46  philippica  阅读(174)  评论(0编辑  收藏  举报