#include <iostream>
#include <vector>
using namespace std;
void next( string str, int len, vector< int >& next )
{
next[0] = -1;
for( int i = 1; i < len; ++i )
{
int j = next[i - 1];
while( str[i] != str[j + 1] && j >= 0 )
{
j = next[j];
}
if( str[i] == str[j + 1] )
next[i] = j+1;
else
next[i] = -1;
}
}
int KMP( string T, int lent, string P, int lenp )
{
vector< int > nex( lenp );
next( P, lenp, nex );
int t = 0,p = 0;
int k = 0;
while( t < lent && p < lenp )
{
if(T[t] == P[p] )
{
t++;
p++;
}
else
{
if(p == 0)
t++;
else
p = nex[p - 1] + 1;
}
}
if( p < lenp )
return -1;
return t - lenp;
}
int main()
{
string T = "bacbababaabcbab";
string P = "acb";
int result = KMP( T, 15, P, 3 );
cout << result << endl;
return 0;
}