Query on a string
Time Limit: 1000/500 MS (Java/Others) Memory Limit:131072/131072 K (Java/Others)
Problem Description
You have two strings S and T in all capitals.
Now anefficient program is requiredto maintain a operationand support a query.
Theoperation C i ch withgiven integer iandcapital letter ch, changes the i-th character of S into ch.
The queryQ i j asks the program to find out, in the substringof S from the i-th character to the j-th one, the total number of T appearing.
Input
Output
For each query, output an integer correponding to the answer.
Output an empty line after each test case.
Sample Input
1
5
AABBABA
AA
Q 1 3
C 6 A
Q 2 7
C 2 B
Q 1
Sample Output
1
2
0
【题意】
给出两个字符串S和T,给出q次操作。
操作1:查询S中[l,r]范围内T出现的次数(可重叠)。
操作2:将S中第i个字符改为ch。
【思路】
我们定义一个num数组,当T在S中出现且最后一个位置是i时,num[i]为1。
那么我们先可以用KMP求出初始的num数组(其实直接暴力求也是可以的),标记一下,然后在求的过程中用树状数组维护。
对于操作1,我们只要查询区间[l+lent-1,r]中num[i]为1的数目,用树状数组的查询操作即可。
对于操作2,我们暴力判断一下是否存在原来可以匹配的最后一个位置失配,有的话取消标记,并更新。是否存在原来失配的位置可以匹配了,加上标记,并更新。
具体细节见代码。
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
#define mst(a,b) memset((a),(b),sizeof(a))
#define rush() int T;scanf("%d",&T);while(T--)
typedef long long ll;
const int maxn = 100005;
const ll mod = 1e9+7;
const int INF = 0x3f3f3f3f;
const double eps = 1e-9;
int num[maxn];
int tree[maxn];
int nex[maxn];
char s[maxn],t[maxn];
int lowbit(int x)
{
return x&(-x);
}
void update(int pos,int val)
{
while(pos<maxn)
{
tree[pos]+=val;
pos+=lowbit(pos);
}
}
int query(int pos)
{
int ans=0;
while(pos>0)
{
ans+=tree[pos];
pos-=lowbit(pos);
}
return ans;
}
void kmp_pre(char *b)
{
int i=0,j=-1;
int len=strlen(b);
nex[0]=-1;
while(i<len)
{
while(j!=-1&&b[i]!=b[j]) j=nex[j];
if(b[++i]==b[++j]) nex[i]=j;
else nex[i]=j;
}
}
void kmp(char *a,char *b)
{
int i=0,j=0;
kmp_pre(b);
int lena=strlen(a),lenb=strlen(b);
while(i<lena)
{
while(j!=-1&&a[i]!=b[j]) j=nex[j];
i++,j++;
if(j>=lenb) //加标记并更新
{
num[i]++;
update(i,1);
}
}
}
int main()
{
rush()
{
int q;
scanf("%d",&q);
mst(num,0);
mst(tree,0);
scanf("%s%s",s+1,t+1);
int lens=strlen(s+1);
int lent=strlen(t+1);
kmp_pre(t+1);
kmp(s+1,t+1);
char op[2],c;
int x,y;
for(int o=0;o<q;o++)
{
scanf("%s",op);
if(op[0]=='Q')
{
scanf("%d%d",&x,&y);
int ans=query(y)-query(x+lent-1-1);
printf("%d\n",ans);
}
else
{
scanf("%d %c",&x,&c);
s[x]=c;
for(int i=max(1,x-lent+1);i<=x;i++)
{
int flag=0;
for(int j=1;j<=lent;j++)
{
if(s[i+j-1]!=t[j]) //不能完成匹配
{
flag=1;
break;
}
}
if(flag==0&&!num[i+lent-1]) //失配->匹配
{
num[i+lent-1]++;
update(i+lent-1,1);
}
else if(flag&&num[i+lent-1]) //匹配->失配
{
num[i+lent-1]--;
update(i+lent-1,-1);
}
}
}
}
puts("");
}
return 0;
}