题目描述
给定
n
个串,
输入格式
第一行包含两个数
n,m
,表示
n
个串,
接下来 n 行,每行一个串。
再接下来
输出格式
输出包含 m 行,即为询问的答案
样例一
input
5 3
except
expert
expect
example
exam
1 2
2 3
4 5
output
2
4
4
限制与约定
对于
对于 100% 的数据, n≤103,m≤105, 每个串的长度 ≤104 .
时间限制: 1s
空间限制: 512MB
思路
裸哈希+二分答案
预处理每个字符串的每前i位的哈希值;
二分答案,若前i位哈希值一样,则调高答案;否则调低;
注意
strlen的时间复杂度是O(n),所以要预处理,O(1)调用,否则会超时;
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
char c[1005][10005];
const unsigned long long P=29;
unsigned long long hs[1005][10005],len[1005];
int a,b,n,m;
using namespace std;
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%s",c[i]);
len[i]=strlen(c[i]);
for(int j=0;j<len[i];j++){
hs[i][j+1]=hs[i][j]*P+(c[i][j]-'a'+1);
}
}
for(int j=1;j<=m;j++){
scanf("%d%d",&a,&b);
int l=0;
int r=min(len[a],len[b])+1;
while(r-l>1){
int mid=(r+l)/2;
if(hs[a][mid]==hs[b][mid]) l=mid;
else r=mid;
}
printf("%d\n",l);
}
return 0;
}