-
Notifications
You must be signed in to change notification settings - Fork 4
/
QUERYSTR.cpp
80 lines (73 loc) · 1.24 KB
/
QUERYSTR.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
// Z-Algorithm for Pattern Matching
// O(n+m)
inline vector<int> calculateZ(string inp)
{
int len = inp.length();
vector<int> Z(len);
int left = 0;
int right = 0;
for(int k = 1; k < len; k++)
{
if(k > right)
{
left = right = k;
while(right < len && inp[right] == inp[right-left])
{
right++;
}
Z[k] = right - left;
right--;
}
else
{
int k1 = k - left;
// inside the Z-Box
if(Z[k1] < right-k+1)
{
Z[k] = Z[k1];
//if the value is inside the Z-box then copy it
}
else
{
// otherwise do more comparisons
left = k;
while(right < len && inp[right] == inp[right-left])
{
right++;
}
Z[k] = right-left;
right--;
}
}
}
return Z;
// Z[i] denotes the length of the longest substring starting from i which is also the prefix of the string.
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
string s; cin >> s;
reverse(s.begin(),s.end());
vector<int> Z = calculateZ(s);
Z[0] = s.length();
reverse(Z.begin(),Z.end());
int q;
scanf("%d",&q);
while(q--)
{
int id;
scanf("%d",&id);
printf("%d\n",Z[id-1]);
}
}
return 0;
}