include vector include iostream include string include algorithm using

 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
#include<vector>
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string s;
cin >> s;
int n = s.size(), l = 0, r = 0;
vector<int> z(n, 0);
for (int i = 1; i < n; ++i)
{
if (i < r)
z[i] = min(z[i - l], r - i + 1);
while (i + z[i] < n && s[z[i]] == s[i + z[i]])
z[i]++;
if (z[i] + i - 1 > r)
{
l = i;
r = z[i] + i - 1;
}
}
for (int i = 0; i < n; ++i)
cout << z[i] << " ";
cout << endl;
return 0;
}