P5768题解
题面
容易想到用 Trie 维护字符串的插入,然后问题就是如何处理询问了。
首先,插入字符串时只用插前
我们这样考虑:
在第
所以,我们发现
看着这个,我们可以想到一个优秀的数据结构:丹钓战 单调栈,不难发现,在查询中,我们可以在单调栈中维护从上至下遍历时每一个匹配的字符串的序号以满足要求。最后得到的就是报文
代码:
#include<bits/stdc++.h>
using namespace std;
int read(){//快读读入IP地址,方便
int x=0;char c=getchar();
while(c<'0'||c>'9')c=getchar();
while(c>='0'&&c<='9')x=(x<<1)+(x<<3)+(c^'0'),c=getchar();
return x;
}
int n,m,l,tot,a,b;
int top,s[320005];//单调栈
char op[10],S[105];
struct Trie{//字典树
int cnt=0;
struct node{
int t[2];
set<int>val;
}c[3200005];
int Build(){
cnt++;
c[cnt].t[0]=c[cnt].t[1]=-1;
c[cnt].val.clear();
return cnt;
}
int Insert(int q,char* s,int id){
int len=strlen(s);
for(int i=0;i<len;i++){
if(c[q].t[s[i]-'0']==-1)c[q].t[s[i]-'0']=Build();
q=c[q].t[s[i]-'0'];
}
c[q].val.insert(id);//标记字符串的编号
return q;
}
void Search(int q,char* S){
int len=strlen(S);
top=0;
for(int i=0;i<len;i++){
if(c[q].t[S[i]-'0']==-1)break;
q=c[q].t[S[i]-'0'];
for(auto x:c[q].val){
while(top>0&&x<s[top])top--;//维护单调栈
s[++top]=x;
}
}
}
}T;
int main()
{
m=read();
T.Build();
while(m--){
scanf("%s",op);
for(int i=1,x;i<=4;i++){
x=read();
for(int j=1;j<=8;j++){
S[(i-1)*8+j]=((x>>(8-j))&1)+'0';//转化为字符串
}
}
if(op[0]=='A'){
l=read();
S[l+1]='\0';
T.Insert(1,S+1,++tot);//插入
}
else{
scanf("%d%d",&a,&b);
T.Search(1,S+1);
int ans=0;
for(int i=1;i<=top;i++){
if(s[i]>=a&&s[i]<=b)ans++;//求出答案
}
printf("%d\n",ans);
}
}
return 0;
}