您的位置:首页 > 其它

poj 2758 Checking the text

2016-08-03 22:13 281 查看
Checking the Text

Time Limit: 8000MS Memory Limit: 65536K

Total Submissions: 3198 Accepted: 698

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

【分析】

(本题参考rlt代码及讲解,讲得还挺清楚hohoho)

网上用后缀数组。。又长又麻烦

用虽然不太靠谱(误)但水数据无敌的哈希做还是不错的

把字符串的每一个以首个字符开头的小段都转换为一个大进制数,就可以用前缀和相减的方式比较单位串是否相同

题中的pow就是单位

【代码】

//poj 2758 Checking the text
#include<iostream>
#include<cstdio>
#include<cstring>
#define fo(i,j,k) for(int i=j;i<=k;i++)
#define of(i,j,k) for(int i=j;i>=k;i--)
using namespace std;
const int maxn=51000,mod=1000000009ll;
int n,m,x,y,len,p[maxn+1];  //p:原字符串中第i个字符的当前下标
char c[maxn+1],f;
long long hash[maxn+1],pow[maxn+1];
void build(int x) {fo(i,x,len) 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);  //m为原串长度(不变动)
build(1);
pow[0]=1;
fo(i,1,maxn)
pow[i]=pow[i-1]*128%mod;
scanf("%d",&n);
fo(i,1,m) p[i]=i;
fo(i,1,n)
{
cin>>f;
if(f=='Q')
{
scanf("%d%d",&x,&y);
printf("%d\n",query(p[x],p[y]));
}
else
{
cin>>f;
scanf("%d",&x);
x=min(x,len+1);
memcpy(c+x+1,c+x,sizeof(char)*(len-x+1));
//这玩意就是把第x个字符及之后的字符整体右移
c[x]=f;
of(j,m,1)
if(p[j]>=x) p[j]++;  //修改下标
else break;
len++;
build(x);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: