Description
LCP就是传说中的最长公共前缀,至于为什么要加上一个大字,那是因为…你会知道的。
首先,求LCP就要有字符串。既然那么需要它们,那就给出n个字符串好了。
于是你需要回答询问大LCP,询问给出一个k,你需要求出前k个字符串中两两的LCP最大值是多少,这就是传说中的大LCP。
Input
第一行一个整数N,Q,分别表示字符串个数和询问次数。
接下来N行,每行一个字符串。
再Q行,每行一个正整数k。
Output
Q行,依次分别表示对Q个询问的答案。
Sample Input
3 3
a
b
ab
1
2
3
Sample Output
0
0
1
Hint
对于30%的数据,字符串总长度不超过10^4,1<=N<=10^3,1<=Q<=10.
接下来30%的数据,字符串总长度不超过10^4,1<=N<=10^3,1<=Q<=1000.
对于100%的数据,字符串总长度不超过10^6,1<=N,Q<=10^5.
做法:建立字典树,每读入一次字符串就更新一次答案然后记录下来
代码如下:
#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#define N 1000007
using namespace std;
int n, m, tot, ans, a[N];
int r[N][26];
bool v[N];
char ch[N];
void insert()
{
int root = 0, len = strlen(ch + 1);
for (int i = 1; i <= len; i++)
{
int id = ch[i] - 'a';
if (!r[root][id]) r[root][id] = ++tot;
if (v[tot]) ans = max(ans, i);
v[tot] = 1;
root = r[root][id];
}
return;
}
int main()
{
scanf("%d%d", &n, &m);
char c = getchar();
for (int i = 1; i <= n; i++)
{
cin >> ch + 1;
insert();
a[i] = ans;
}
for (int i = 1; i <= m; i++)
{
int x;
scanf("%d", &x);
printf("%d\n", a[x]);
}
}