【数论】中缀表达式转化为后缀表达式
2021-03-09 16:51:00 # ACM

习自

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
#define LL long long
#define ll long long
#define ULL unsigned long long
#define ls rt<<1
#define rs rt<<1|1
#define MS 100009
#define INF 1e18
#define mod 998244353
#define Pi acos(-1.0)
#define Pair pair<LL,LL>
#define eps 1e-9

LL n,m,k;
char s[MS]; // 字符串读入中缀表达式
LL hs; // 中缀表达式的len
stack<LL> fu;
LL prfu[300]; // 定义 + - * / ^ 优先级
LL hz[MS],thz; // 存放后缀表达式 ,若第i位为字符则 vf[i] = 1;
LL vf[MS]; // 标记 1 为符 ;

void init_prfu(){ // 定义 + - * / ^ 优先级
prfu['('] = prfu[')'] = 0;
prfu['+'] = prfu['-'] = 1;
prfu['*'] = prfu['/'] = 2;
prfu['^'] = 3;
}

void s_hz(){ // 得到 后缀表达式 hz[1...thz] ,其中字符以数字表示 ,vf[i]=1 表示 hz[i] 为字符
hs = strlen(s);
LL num = 0;
LL flnum = 0;
for(int i=0;i<hs;i++){
if('0' <= s[i] && s[i] <= '9'){
flnum = 1;
num = num*10+(s[i]-'0');
continue;
}
else if(flnum) hz[++thz] = num ,num = flnum = 0;
if(fu.empty()){
fu.push(s[i]);
continue;
}
if(s[i] == '(') fu.push(s[i]);
else if(s[i] == ')'){
while(fu.top() != '('){
hz[++thz] = fu.top();
vf[thz] = 1;
fu.pop();
}
fu.pop();
}
else{
while(!fu.empty() && prfu[s[i]] <= prfu[fu.top()]){
hz[++thz] = fu.top();
vf[thz] = 1;
fu.pop();
}
fu.push(s[i]);
}
}
if(flnum) hz[++thz] = num ,num = flnum = 0;
while(!fu.empty()){
hz[++thz] = fu.top();
vf[thz] = 1;
fu.pop();
}
}

int main(){
ios::sync_with_stdio(false);
init_prfu();
cin >> s;
s_hz();

for(int i=1;i<=thz;i++){
if(vf[i]) printf("%c ",hz[i]);
else printf("%lld ",hz[i]);
}
printf("\n");


return 0;
}

/*
88-(333+22*6)/55+4

88 333 22 6 * + 55 / - 4 +
*/
Prev
2021-03-09 16:51:00 # ACM
Next