题解:[USACO15FEB] Censoring S

洛谷P4824

Posted by TH911 on January 21, 2025

题目传送门

前置知识:KMP

又水一道 提高+/省选−

强化版:[USACO15FEB] Censoring G

弱化版

很明显,可以使用 [USACO15FEB] Censoring G 的代码,将数组大小从 $10^5$ 改为 $10^6$ 即可。

参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//#include<bits/stdc++.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<iomanip>
#include<cstdio>
#include<string>
#include<vector>
#include<cmath>
#include<ctime>
#include<deque>
#include<queue>
#include<stack>
#include<list>
using namespace std;
constexpr const int T=1e6,S=1e6;
char t[T+1],s[S+1]; 
struct trie{
	struct node{
		int m[26];
		int len,fail;
	}t[S+1];

	void insert(char *s){
		int p=0;
		for(int i=0;s[i];i++){
			if(!t[p].m[s[i]-'a']){
				static int top;
				t[p].m[s[i]-'a']=++top;
			}
			p=t[p].m[s[i]-'a'];
		}int len=strlen(s);
		t[p].len = max(t[p].len,len);
	}
	void build(){
		queue<int>q;
		for(int i=0;i<26;i++){
			if(t[0].m[i]){
				q.push(t[0].m[i]);
			}
		}
		while(q.size()){
			int p=q.front();q.pop();
			for(int i=0;i<26;i++){
				if(t[p].m[i]){
					t[t[p].m[i]].fail = t[t[p].fail].m[i];
					q.push(t[p].m[i]);
				}else{
					t[p].m[i] = t[t[p].fail].m[i];
				}
			}
		}
	}
	void query(char *s){
		int p=0;
		vector<int>path;
		vector<char>ans;
		for(int i=0;s[i];i++){
			p=t[p].m[s[i]-'a'];
			path.push_back(p);
			ans.push_back(s[i]);
			if(t[p].len){
				path.resize(path.size()-t[p].len);
				ans.resize(ans.size()-t[p].len); 
				p=path.back();
			}
		}
		for(char &i:ans){
			putchar(i);
		}putchar(10);
	}
}trie;
int main(){
	/*freopen("test.in","r",stdin);
	freopen("test.out","w",stdout);*/
	
	scanf("%s",t);
//	int n;
//	scanf("%d",&n);
//	while(n--){
		scanf("%s",s);
		trie.insert(s);
	/*}*/trie.build();
	trie.query(t);
	
	/*fclose(stdin);
	fclose(stdout);*/
	return 0;
}

KMP 匹配

使用 KMP 算法代替 AC 自动机/Trie 图即可。

因为 AC 自动机会多带一个 $26$ 的常数。

但是我懒得打 KMP 了……