求CFG的LR(0)NFA
#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <set> struct rule { char from; std::string to; rule() {} rule(const char *str) { from = str[0]; to = str + 5; } }; struct term { char from; std::string to; int pos; std::string left; std::string right; term(){}; term(const rule &r, int p) { from = r.from; to = r.to; pos = p; left = std::string(r.to, 0, p); right = std::string(r.to, p); } void out() { std::cout<<"{"<<from<<" -> "<<left<<"."<<right<<"}"; } }; struct edge { int from; int to; char label; edge(){} edge(int from, int to, char label) { this->from = from; this->to = to; this->label = label; } }; struct subset { std::set<int> s; }; bool ter[128]; rule r[10]; term t[100]; edge e[1000]; char sb[128][10]; int main() { char str[100]; int n = 0; int m = 0; int k = 0; memset(ter, 0, sizeof(term)); for (int i=0; i < 128; ++i) { strcpy(sb[i], ""); sb[i][0] = i; } strcpy(sb[0], "empty"); while (gets(str)) r[n++] = rule(str); for (int i=0; i < n; ++i) { ter[r[i].from] = true; int l = r[i].to.length(); for (int j=0; j <= l; ++j) t[m++] = term(r[i], j); } for (int i=0; i < m; ++i) if (t[i].pos < t[i].to.length()) { char x = t[i].to[t[i].pos]; for (int j=0; j < m; ++j) { if (t[i].from == t[j].from && t[i].to == t[j].to && t[i].pos + 1 == t[j].pos) e[k++] = edge(i, j, x); if (ter[x] && t[j].from == x && t[j].pos == 0) e[k++] = edge(i, j, 0); } } for (int i=0; i < k; ++i) { std::cout<<sb[e[i].label]<<":/t/t"; t[e[i].from].out(); std::cout<<" -> "; t[e[i].to].out(); std::cout<<std::endl; } return 0; }
Input 1
S -> E E -> E+T E -> T T -> T*F T -> F F -> (E) F -> n
Output 1
E: {S -> .E} -> {S -> E.} empty: {S -> .E} -> {E -> .E+T} empty: {S -> .E} -> {E -> .T} empty: {E -> .E+T} -> {E -> .E+T} E: {E -> .E+T} -> {E -> E.+T} empty: {E -> .E+T} -> {E -> .T} +: {E -> E.+T} -> {E -> E+.T} T: {E -> E+.T} -> {E -> E+T.} empty: {E -> E+.T} -> {T -> .T*F} empty: {E -> E+.T} -> {T -> .F} T: {E -> .T} -> {E -> T.} empty: {E -> .T} -> {T -> .T*F} empty: {E -> .T} -> {T -> .F} empty: {T -> .T*F} -> {T -> .T*F} T: {T -> .T*F} -> {T -> T.*F} empty: {T -> .T*F} -> {T -> .F} *: {T -> T.*F} -> {T -> T*.F} F: {T -> T*.F} -> {T -> T*F.} empty: {T -> T*.F} -> {F -> .(E)} empty: {T -> T*.F} -> {F -> .n} F: {T -> .F} -> {T -> F.} empty: {T -> .F} -> {F -> .(E)} empty: {T -> .F} -> {F -> .n} (: {F -> .(E)} -> {F -> (.E)} empty: {F -> (.E)} -> {E -> .E+T} empty: {F -> (.E)} -> {E -> .T} E: {F -> (.E)} -> {F -> (E.)} ): {F -> (E.)} -> {F -> (E).} n: {F -> .n} -> {F -> n.}
Input 2
S -> E E -> (E)E E ->
Output 2
E: {S -> .E} -> {S -> E.} empty: {S -> .E} -> {E -> .(E)E} empty: {S -> .E} -> {E -> .} (: {E -> .(E)E} -> {E -> (.E)E} empty: {E -> (.E)E} -> {E -> .(E)E} E: {E -> (.E)E} -> {E -> (E.)E} empty: {E -> (.E)E} -> {E -> .} ): {E -> (E.)E} -> {E -> (E).E} empty: {E -> (E).E} -> {E -> .(E)E} E: {E -> (E).E} -> {E -> (E)E.} empty: {E -> (E).E} -> {E -> .}