题解 P5826 【【模板】子序列自动机】
【可持久化线段树】【P5826】【模板】子序列自动机
Description
给定一个序列
Limitations
序列
Solution
题外话:有关这道题的难度,我觉得大概到不了紫色,但是可持久化线段树的板子是紫色的,所以就设成了紫色
update:被神仙用 std::vector + 二分给碾过去了,那就改成绿色趴……不过为什么改难度之前提交记录清一色可持久化线段树,改了之后清一色二分啊,泥萌是在看难度想做法嘛
Algorithm 1
考虑对于一个询问序列
考虑寻找字典序最小的
这样的话每次询问时,最多扫描
Algorithm 2
考虑对
同样运用 Algorithm 1 中的思想,对于一个字符串
考虑我们对
for i : m do
trans[n][i] <- -1
end
for i = n : 1 do
for j = 1 : m do
trans[i - 1][j] <- trans[i][j]
end
trans[i - 1][A[i]] <- i
end
其中
而对一个字符串
Function check:
pos <- 0
ret <- true
for i = 1 : L do
pos <- trans[pos][B[i]]
if pos == -1 then
ret <- false
break
endif
end
return ret
end Func
注意到这样构造自动机的时间复杂度为
Algorithm 3
注意到构造自动机时,第
Code
Algorithm 2
代码来自 @_皎月半洒花
#include <cstdio>
#include <vector>
#include <cstring>
#include <iostream>
#define MAXN 200010
using namespace std ;
int L, N, M, Q, S[MAXN], nxt[MAXN][102] ;
void build(){
for (int i = 1 ; i <= M ; ++ i)
nxt[L + 2][i] = nxt[L + 1][i] = L + 2 ;
for (int i = L ; i ; -- i)
memcpy(nxt[i - 1], nxt[i], sizeof(nxt[i])), nxt[i - 1][S[i]] = i ;
}
int qr(){
char c = getchar() ;
int res = 0 ; while (!isdigit(c)) c = getchar() ;
while (isdigit(c)) res = (res << 1) + (res << 3) + c - 48, c = getchar() ;
return res ;
}
int main(){
int i, j, k, emm ;
cin >> emm >> N >> Q >> M ; L = N ;
for (i = 1 ; i <= L ; ++ i) scanf("%d", &S[i]) ; build() ;
for (i = 1 ; i <= Q ; ++ i){
N = qr() ; int st = 0, ans = 0 ;
for (j = 1 ; j <= N ; ++ j){
k = qr(), st = nxt[st][k] ;
if (!st){
while (j < N)
++ j, emm = qr() ;
ans = 1 ;
}
// cout << st << endl ;
}
printf(ans ? "No\n" : "Yes\n") ;
}
return 0 ;
}
Algorithm 3
#include <cstdio>
template <typename T>
inline void qr(T &x) {
char ch;
do ch = getchar(); while ((ch > '9') || (ch < '0'));
do x = x * 10 + (ch ^ 48), ch = getchar(); while ((ch >= '0') && (ch <= '9'));
}
const int maxn = 100005;
struct Tree {
Tree *ls, *rs;
int l, r, v;
Tree(const int L, const int R) : l(L), r(R), v(-1) {
if (l != r) {
int mid = (l + r) >> 1;
ls = new Tree(l, mid);
rs = new Tree(mid + 1, r);
}
}
Tree(Tree *pre, const int P, const int V) : l(pre->l), r(pre->r), v(0) {
if (l == r) {
v = V;
} else {
if (pre->ls->r >= P) {
rs = pre->rs;
ls = new Tree(pre->ls, P, V);
} else {
ls = pre->ls;
rs = new Tree(pre->rs, P, V);
}
}
}
int query(const int x) {
if (this->l == this->r) {
return this->v;
} else {
return (this->ls->r >= x) ? this->ls->query(x) : this->rs->query(x);
}
}
};
Tree *rot[maxn];
int tp, n, q, m;
int MU[maxn];
int main() {
qr(tp); qr(n); qr(q); qr(m);
rot[n] = new Tree(1, m);
for (int i = 1; i <= n; ++i) {
qr(MU[i]);
}
for (int i = n; i; --i) {
rot[i - 1] = new Tree(rot[i], MU[i], i);
}
for (int L, x, pos; q; --q) {
L = pos = 0; qr(L);
while ((L--) && (pos != -1)) {
x = 0; qr(x);
if ((pos = rot[pos]->query(x)) == -1) {
while (L--) {
qr(x);
}
break;
}
}
puts((~pos) ? "Yes" : "No");
}
return 0;
}
appreciation
感谢验题人:@_皎月半洒花 @water_lift
感谢本文的审核与校对:@Dusker