跳到正文

题解

题解:P10526 [XJTUPC2024] 命令行

ViynaNokphia约 3 分钟
原文
文章信息与版本

文章信息

发布
2024年11月3日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 3 分钟
获赞
2
题目
P10526

版本

  1. v1当前

题意:实现一个包括 Tab 补全、Backspace 功能的简易 shell 的部分功能(只需找到要执行哪一条指令)。

因为实现 Tab 补全需要找到很多字符串最长公共前缀,然后你会发现用字典树去维护这个东西好像还挺方便的。具体而言,可在字典树上一直跳到符合条件(即,这个点之后的第一个分岔点或者有命令的点)的点,但是这样会超时。然后我们发现每个节点 uu 跳到的点 nextu{\rm next}_u 是固定的,然后它是可以深搜预处理出来的,处理完后直接跳就好了。

对于 Backspace 操作,给每一个节点维护一个父亲就好啦。

然后对于不在树上的输入串我们也可以给他搬到树上,这样维护起来会很容易。

C++
struct Node {
	Node* child[26] = { nullptr };
	Node* fa = nullptr;
	Node* nxt = nullptr;
	int cmdid = -1;
};

auto root = new Node;

void insert(int x, const string &s)
{
	auto cur = root;
	for (auto ch : s) {
		if (!cur->child[ch - 'a']) {
			cur->child[ch - 'a'] = new Node;
			cur->child[ch - 'a']->fa = cur;
		}
		cur = cur->child[ch - 'a'];
	}
	cur->cmdid = x;
}

Node* cal_nxt(Node* u)
{
	int size = 0;
	for (int i = 0; i < 26; i++) size += !!u->child[i];
	if (size == 1 && u->cmdid == -1) {
		for (int i = 0; i < 26; i++) {
			if (u->child[i]) {
				return u->nxt = cal_nxt(u->child[i]);
			}
		}
		// Never goes here
		return nullptr;
	}
	for (int i = 0; i < 26; i++) {
		if (u->child[i]) {
			cal_nxt(u->child[i]);
		}
	}
	return u->nxt = u;
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	cin >> n >> m;
	string cmd;
	for (int i = 1; i <= n; i++) {
		cin >> cmd;
		insert(i, cmd);
	}
	cal_nxt(root);
	char ch;
	Node* cur = root;
	for (int i = 1; i <= m; i++) {
		cin >> ch;
		if (ch == 'T') {
			cur = cur->nxt;
		} else if (ch == 'B') {
			if (cur->fa) cur = cur->fa;
		} else if (ch == 'E') {
			cout << cur->cmdid << ' ';
			cur = root;
		} else {
			if (!cur->child[ch - 'a']) {
				Node* x = new Node;
				x->nxt = x;
				x->fa = cur; 
				cur->child[ch - 'a'] = x; 
			}
			cur = cur->child[ch - 'a'];
		}
	}
}
原文