线上原理实验

判断终结符和非终结符

#include<bits/stdc++.h>
using namespace std;
int main() {
	int n;
	cin >> n;
	vector<char> a, b;
	map<char, bool>st;
	st['|'] = true;//分隔符,文法推出的
	st[' '] = true;//空格不添加
	st[64] = true;//64为@,表示空
	for (int i = 0; i < n; i++) {
		string s;
		cin >> s;//输入每一行的文法

		for (int j = 0; j < s.length(); j++) {
			if (s[j] == '-' || s[j] == '>')
				continue;
			//我觉得还是直接这样比较简单

			if (s[j] >= 'A' && s[j] <= 'Z') {//非终结符
				if (st[s[j]] == 0)//等于1则为存在,不重复添加
					a.push_back(s[j]), st[s[j]] = 1;
				//在a的尾部增加元素,并让st中此非终结符为1
			}
			else {
				if (st[s[j]] == 0) {
					b.push_back(s[j]), st[s[j]] = 1;
				}
			}
		}
	}

	cout << "终结符为" << endl;
	for (auto vt : b)//遍历容器中的元素
		cout << vt << " ";
	cout << endl;
	cout << "非终结符为" << endl;
	for (auto vn : a)
		cout << vn << " ";
	return 0;
}

DFA字符的转换

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
map<char, int>mp[1005];
//一个数组,每个数字表示一个点,
//里面用map存转换函数

int a[10005];//为终态,终态是数字

int main() {
	int n, st;
	cin >> st >> n;
	//st是初态

	for (int i = 1; i <= n; i++) {
		int x;//终态集合
		cin >> x;
		a[x] = 1;
	}

	int m;
	cin >> m;//转换函数数量
	for (int i = 1; i <= m; i++) {
		char c;
		int u, v;//u经c到v
		cin >> u >> c >> v;
		mp[u][c] = v;
	}

	string s;
	cin >> s;//判断的字符
	vector<int> ans;
	ans.push_back(st);
	//需要输出转换的路径,用vector存放结点

	int u = st;
	for (int i = 0; i < s.length(); i++) {//s还没判断完
		char now = s[i];//现在是到s的第几个字符

		if (mp[u][now]) {//u这个点的转换函数存在
			ans.push_back(mp[u][now]);
			u = mp[u][now];//移动到下一个点
		}
		else {
			cout << "False";
			return 0;
		}
	}

	if (!a[u]) {//判断完毕,u不是终态
		cout << "False";
		return 0;
	}

	for (int i = 0; i < ans.size()-1; i++)
		cout << ans[i] << "->";
	cout << ans.back() << endl;
	//在这里注意vector最后一个元素的输出
	//因为有‘->’,如果输出到尾,那么还会输出一个,不符合标准
	cout << "True" << endl;
	return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值