P10526 [XJTUPC2024] 命令行题解

题目大意

  1. 对于一个字符串 $ s $ 在输入的最后一行读入的字符,如个字符不为 $ E \(,\) T \(,\) B $ 那么这一个字符就添加至字符串 $ s $ 的末尾。

  2. 对于操作 $ B $ 那么执行删除字符串 $ s $ 的最后一个字符,如果 $ s $ 为空那么跳过这个操作。

  3. 对于操作 $ T $ 找到一个以字符串 $ s $ 为前缀的字符串,要求这一个字符串为可以找到所有字符串当中的最长且为任意一个字符串的前缀。如果 $ s $ 没有前缀就跳过。

  4. 对于操作 $ E $ 如果有一个字符串等于当前的 $ s $ 那么输出这串字符串的编号,否则输出 $ -1 $。然后将 $ s $ 清空。

思路

对于查询与添加字符串的维护我们有一个非常好的算法字典树,对于每一次查询我们写一个 $ fa_i $ 表示在字典树的编号中这个标号的父亲,一个 $ end_i $ 在字典树编号中这个标号是否为一个字符串的最后一个字符,至此我们的思路完了,所以我觉得屏幕前的你可以去自己写代码了。

注意

  1. 对于 $ fa $ 数组与 $ end $ 数组的大小开 $ maxn $ 就行了不然会爆空间。

  2. 如果根从 $ 0 $ 开始记得把 $ fa $ 数组初始化成负数。

  3. $ end $ 数组也需要初始化负数,不然会答案错误

  4. 输出 $ -1 $ 时记得打一个空格

Code:

#include <algorithm>
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <queue>
#define sc(ppt) scanf("%lld" , &ppt)
#define ll long long
#define int long long
#define prt printf
using namespace std;

const int maxn = 1e6 + 1;
int n , m;
int bj = 0 , pop = 0;
char s[5000001];
struct Tree{
	int next[maxn][30] , cnt = 0 , fa[maxn * 20] , end[maxn] , t[maxn];
	int csh(char cap){ return cap - 'a' + 1;}
	void insert(string A , int num){
		int u = 0 , len = A.size();
		for(int i=0 ; i<len ; i++){
			int v = csh(A[i]);
			if(! next[u][v]) next[u][v] = ++ cnt;
			fa[next[u][v]] = u;
			u = next[u][v];
		}
		end[u] = num;
	}
	int get_ans(int u){ // dfs
		int res = 0;
		for(int i=1 ; i<=26 ; i++){
			res += !! next[u][i];	
		}
		if(res > 1 || ~end[u]){
			for(int i=1 ; i<=26 ; i++) if(next[u][i]) get_ans(next[u][i]);
			return t[u] = u;
		}
		for(int i=1 ; i<=26 ; i++){
			if(next[u][i]) return t[u] = get_ans(next[u][i]);
		}
		return 202521;
	}
}tree; 
	
signed main(){
	sc(n) ; sc(m) ; memset(tree.fa , -2 , sizeof tree.fa) ; memset(tree.end , -1 , sizeof tree.end); 
	for(int i=1; i<=n ; i++){
		cin >> s ;
		tree.insert(s , i);	
	}
	tree.t[0] = tree.get_ans(0);
	cin >> s;
	for(int i=0 ; i<m ; i++){
		if(s[i] == 'E'){
			if(bj) prt("-1 ");
			else prt("%lld " , tree.end[pop]);
			pop = bj = 0;
		}
		else if(s[i] == 'T'){
			if(! bj) pop = tree.t[pop];
		}
		else if(s[i] == 'B'){
			if(bj) -- bj;
			else if(pop) pop = tree.fa[pop];	
		} 
		else{
			if(bj || !tree.next[pop][tree.csh(s[i])]) ++bj;
			else pop = tree.next[pop][tree.csh(s[i])];
		}
	}
	return 0;
}

posted @ 2024-05-30 21:25  CaoSheng  阅读(20)  评论(0)    收藏  举报