Description
输入开始符号,非终结符,终结符,产生式
压缩自产生式文法和不可达文法后,按非终结符顺序输出产生式;
Input
输入开始符号;
非终结符个数,非终结符,空格符分隔;
终结符个数,终结符,空格符分隔;
产生式的个数,各产生式的左边和右边符号,空格符分隔;
Output
delete self production:自产生式文法
unreached Vn:不可达非终结符
delete production:不可达产生式
delete VN:不可达非终结符
G[开始符号]:
压缩自产生式文法和不可达文法后,按非终结符顺序输出各产生式;
Sample input:
Z
8 Z E F P G T Q S
3 + * i
18
Z E+T
E E
P G
F F
P G
G G
T T*i
Q E
S i
E S+F
F FP
G GG
Q E+F
E T
F P
G F
Q T
Q S
Sample output:
delete self production:E::=E
delete self production:F::=F
delete self production:G::=G
unreached Vn:Q
delete production:Q::=E
delete production:Q::=E+F
delete production:Q::=T
delete production:Q::=S
delete VN:Q
G[Z]:
Z::=E+T
E::=S+F | T
F::=FP | P
P::=G | G
G::=GG | F
T::=T*i
S::=i
Code:
本程序主要有由四个模块组成
模块一功能:输入并存储数据
模块二功能:找到自产生式文法并删除和输出相关数据
模块三功能:找到不可达非终结符并删除不可达产生式同时输出相关数据
模块四功能:输出产生式
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
// input data
string S;
struct { int Nv;string VN[10];} Vns;
struct { int Nt;string VT[10];} Vts;
struct { int Np;string PL[20],PR[20];} ps;
vector<string> youbu;
cin >> S;
cin >> Vns.Nv;
for(int i=0;i<Vns.Nv;i++)
cin >> Vns.VN[i];
cin >> Vts.Nt;
for(int i=0;i<Vts.Nt;i++)
cin >> Vts.VT[i];
int N;
cin >> N;
std::map<string, vector<string> > m;
while(N--){
string a;
string b;
cin >> a >> b;
m[a].push_back(b);
youbu.push_back(b);
}
// handle data
// find self production
for (int i = 0; i < Vns.Nv; ++i)
{
int j = 0;
auto it = m[Vns.VN[i]].begin();
while(it != m[Vns.VN[i]].end()){
if(*it == Vns.VN[i]){
m[Vns.VN[i]].erase(it);
cout << "delete self production:";
cout << Vns.VN[i] << "::=" << Vns.VN[i] << endl;
}
else{
it++;
}
}
}
// find unreached Vn
std::vector<string> s;
std::vector<string> unreached;
for(int i = 0; i < Vns.Nv ; i++){
s.push_back(Vns.VN[i]);
}
auto it = s.begin();
while(it != s.end()){
string c = *it;
int flag = 0;
if(c == S){
flag = 1;
}
for(int i = 0; i < youbu.size(); i++){
auto found = youbu[i].find(c);
if (found != std::string::npos){
flag = 1;
break;
}
}
if(flag == 0){
cout << "unreached Vn:" << c << endl;
for(int i = 0; i < m[c].size(); i++){
cout << "delete production:";
cout << c << "::=" << m[c][i] << endl;
}
cout << "delete VN:" << c << endl;
s.erase(it);
}
else{
it++;
}
}
// output G[start]
cout << "G[" << S << "]:" << endl;
for (int i = 0; i < s.size(); ++i)
{
cout << s[i] << "::=";
for(int j = 0; j < m[s[i]].size(); j++){
if(j < m[s[i]].size()-1)
cout << m[s[i]][j] << " | ";
else
cout << m[s[i]][j];
}
cout << endl;
}
return 0;
}