GRE Words Revenge
题意:
一个01字符串机器,两种操作:
- +String 表示增加String串进机器里
- ?String 表示查询String串有多少个子串在机器里面
要求强制在线,给出的串要循环左移lastans次。lastans是上次查询的答案。
思路:
若没有增加操作,可以看出这是个AC自动机的裸题,于是就采用《浅谈数据结构的几个非经典解法》论文中说的二进制分组,巧妙的用一个log的代价暴力实现在线,复杂度证明还是没看懂,不过跑得倒是挺快,代码应该比较简单,认真看看就明白了,其实就是开log个AC自动机,有点二项堆的意思,妙。
mdzz写错了循环位移wa了5发。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MBIT = 30;
const int MX = 2e5+5;
struct lowbit_trie{
int son[MX][2], end[MX], fail[MX];
int root[MBIT], size[MBIT], bitcnt, alloc;
string str[100005]; int scnt;
set<string>st;
void init(){
alloc = scnt = bitcnt = 0;
memset(root, 0, sizeof(root));
memset(size, 0, sizeof(size));
st.clear();
}
int newnode(){
memset(son[++alloc], 0, sizeof(son[alloc]));
end[alloc] = fail[alloc] = 0;
return alloc;
}
void build(int rt){
queue<int>q;
fail[rt] = rt;
for(int i = 0; i < 2; ++i){
if(!son[rt][i]) son[rt][i] = rt;
else fail[son[rt][i]] = rt, q.push(son[rt][i]);
}
while(!q.empty()){
int u = q.front(); q.pop();
end[u] += end[fail[u]];
for(int i = 0; i < 2; ++i){
if(!son[u][i]) son[u][i] = son[fail[u]][i];
else fail[son[u][i]] = son[fail[u]][i], q.push(son[u][i]);
}
}
}
void rebuild(int l, int r, int &rt){
rt = newnode();
for(int i = l; i <= r; ++i){
int p = rt;
for(int j = 0; j < str[i].length(); ++j){
if(son[p][str[i][j]-'0'] == 0) son[p][str[i][j]-'0'] = newnode();
p = son[p][str[i][j]-'0'];
}
end[p]++;
}
build(rt);
}
void insert(char *s){
if(st.count(s) == 1) return;
st.insert(s);
str[++scnt] = string(s);
size[++bitcnt] = 1, root[bitcnt] = newnode();
while(bitcnt >= 2 && size[bitcnt] == size[bitcnt-1]){
size[--bitcnt] *= 2;
}
alloc = root[bitcnt]-1;
rebuild(scnt-size[bitcnt]+1, scnt, root[bitcnt]);
}
ll _query(char *s, int rt){
int p = rt; ll res = 0;
for(int i = 0; s[i]; ++i){
p = son[p][s[i]-'0'];
res += end[p];
}
return res;
}
ll query(char *s){
ll res = 0;
for(int i = 1; i <= bitcnt; ++i){
res += _query(s, root[i]);
}
return res;
}
}ac;
char tmp[5000005];
char ss[5000005];
void getss(ll k){
scanf("%s", tmp);
int len = strlen(tmp+1);
for(int i = 0; i < len; ++i){
ss[i] = tmp[1+(i+k)%len];
}
ss[len] = '\0';
}
int main(){
int T, ca = 1;
scanf("%d", &T);
while(T--){
int n; ll last = 0;
scanf("%d%*c", &n);
ac.init();
printf("Case #%d:\n", ca++);
for(int i = 0; i < n; ++i){
getss(last);
if(tmp[0] == '+') ac.insert(ss);
else printf("%lld\n", last = ac.query(ss));
}
}
}