赞
踩
注:编译原理
对照分析表实现
// sicily 2, complier course
#include <iostream>
#include <vector>
#include <cstring>
#include <string.h>
#include <iomanip>
#include <stack>
using namespace std;
#define MAXSIZE 1000
string result[MAXSIZE][MAXSIZE];
string expr[MAXSIZE];
vector<char> vt;
vector<char> vn;
string queStr;
int findrow(char ch) {
int n = vn.size();
for (int i = 0; i < n; ++i) {
if (vn[i] == ch)
return i;
}
}
int findcol(char ch) {
int n = vt.size();
for (int i = 0; i < n; ++i) {
if (vt[i] == ch)
return i;
}
}
void print(int n, stack<char> st) {
cout << "#";
for (int i = 0; i < n; ++i) {
cout << queStr[i];
}
cout << " & ";
while (!st.empty()) {
cout << st.top();
st.pop();
}
cout << "#" << endl;
}
int main() {
char start;
char ch;
// initialize
for (int i = 0; i < MAXSIZE; ++i)
expr[i] = "";
for (int i = 0; i < MAXSIZE; ++i) {
for (int j = 0; j < MAXSIZE; ++j) {
result[i][j] = "";
}
}
// vt and vn
int vnnum, vtnum, exprnum, pronum;
cin >> start;
cin >> vnnum;
for (int i = 0; i < vnnum; ++i) {
cin >> ch;
vn.push_back(ch);
}
cin >> vtnum;
for (int i = 0; i < vtnum; ++i) {
cin >> ch;
vt.push_back(ch);
}
vt.push_back('#');
vtnum++;
// expression
cin >> exprnum;
int seq;
string str;
for (int i = 0; i < exprnum; ++i) {
cin >> seq >> ch >> str;
expr[seq] = str;
}
// production expression
char vnchar, vtchar;
int relseq;
cin >> pronum;
for (int i = 0; i < pronum; ++i) {
cin >> seq >> vnchar >> vtchar >> relseq;
result[findrow(vnchar)][findcol(vtchar)] = expr[relseq];
}
// string
string temp = "";
char head;
cin >> queStr;
int strSize = queStr.size();
stack<char> st;
stack<char> printSt;
st.push('E');
int i = 0;
print(i, st);
while (queStr[i] != '#') {
ch = queStr[i];
while (!st.empty()) {
head = st.top();
// match sucessfully
st.pop();
if (head == ch) {
i++;
print(i, st);
break;
} else {
// substitute
temp = result[findrow(head)][findcol(ch)];
if (temp != "k" && temp != "") {
for (int k = temp.length() - 1; k >= 0; --k) {
st.push(temp[k]);
}
}
print(i, st);
}
}
}
// pop the stack until it is empty
while (!st.empty()) {
head = st.top();
st.pop();
print(i, st);
}
return 0;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。