Description
Wind’s birthday is approaching. In order to buy a really really fantastic gift for her, Jiajia has to take a boring yet money-making job - a text checker.
This job is very humdrum. Jiajia will be given a string of text what is English letters and he must count the maximum number of letters that can be matched, starting from two position of the current text simultanously. The matching proceeds from left to right, one character by one.
Even worse, sometimes the boss will insert some characters before, after or within the text. Jiajia wants to write a program to do his job automatically, this program should be fast enough, because there are only few days to Wind’s birthday.
Input
The first line of input file contains initial text.
The second line contains then number of commands n. And the following n lines describe each command. There are two formats of commands:
I ch p: Insert a character ch before the p-th. if p is larger than the current length of text, then insert at end of the text.
Q i j: Ask the length of matching started from the i-th and j-th character of the initial text, which doesn’t include the inserted characters.
You can assume that the length of initial text will not exceed 50000, the number of I command will not exceed 200, the number of Q command will not exceed 20000.
Output
Print one line for each Q command, contain the max length of matching.
Sample Input
abaab
5
Q 1 2
Q 1 3
I a 2
Q 1 2
Q 1 3
Sample Output
0
1
0
3
hash+二分(一点)
每插入一次将插入位置之后的hash值重算一遍。
查询时,二分最大公共前缀位置,若可以匹配,继续向后找,否则,向前。
注意:输入的次序是按照初始字符串走的,而不是之后修改的。
#include
#include
#include
#include
#define mod 1000000009ll
using namespace std;
const int maxn=51000;
int n,m,len,p[maxn];
char c[maxn];
long long hash[maxn],pow[maxn];
void build(int x)
{
for(int i=x;i<=len;i++)
hash[i]=(hash[i-1]*128+c[i])%mod;
}
int query(int x,int y)
{
int l=0,r=len-max(x,y)+1;
while(l<=r)
{
int mid=l+r>>1;
if((hash[x+mid-1]-hash[x-1]*pow[mid]%mod+mod)%mod==(hash[y+mid-1]-hash[y-1]*pow[mid]%mod+mod)%mod)
l=mid+1;
else
r=mid-1;
}
return r;
}
int main()
{
scanf("%s",c+1);
m=len=strlen(c+1);
build(1);
pow[0]=1;
for(int i=1;i<=maxn;i++)
pow[i]=pow[i-1]*128%mod;
scanf("%d",&n);
for(int i=1;i<=m;i++)
p[i]=i;
for(int i=1;i<=n;i++)
{
int x,y;
char tmp[11];
scanf("%s",tmp);
if(tmp[0]=='Q')
{
scanf("%d%d\n",&x,&y);
printf("%d\n",query(p[x],p[y]));
}
else
{
scanf("%s%d",tmp,&x);
if(x>len)
x=len+1;
memcpy(c+x+1,c+x,sizeof(char)*(len-x+1));
c[x]=tmp[0];
for(int j=m;j>=1;j--)
{
if(p[j]>=x)
p[j]++;
else
break;
}
len++;
build(x);
}
}
return 0;
}